I'm very new to scripting and when I use the script below it only changes one of the parts. They are all named the same and grouped together. Thanks for helping!
function Colour() script.Parent.Parent.Light1.BrickColor = BrickColor.Red() end script.Parent.ClickDetector.MouseClick:connect(Colour)
To get all the parts inside a model, we use
model:GetChildren()
To loop through the parts found in the descendant, we will use
for loop
, particularly,for i, v in pairs do
. The i and v are short forindex
, andvalue
. This is the loop you would use to cycle through what we call thetables
loops
?When there are one or more objects in the workspace and we want to change both of their properties in once, instead of repeating the code you wrote the x amount of times. Basically it is a life saver.
model = game:GetService("Workspace").modelName modelChildren = model:GetChildren()
^ This above code gets all the parts found inside the modelName.
-- Declaration Section local model = game:GetService("Workspace").Parts local clickButton = game:GetService("Workspace").click -- Processing Section local function clickToChangeColour () for _, child in pairs(model:GetChildren()) do child.BrickColor = BrickColor.Red() end end -- Connecting Section clickButton.ClickDetector.MouseClick:Connect(clickToChangeColour)
What the above code does is, the for loop cycles through the model's children and changes the properties. In your case, it is going to change the brick's properties.
loops
rather than just copying the above code. Here are few links you might want to check out for better understanding.You need to get all the Lights and in order to do that you'll need to use a table.
local ParentOfAllTheLights = workspace -- or where all your lights are local myTable = ParentOfAllTheLights:GetChildren() --This will form your table function Colour() --Use a for loop to check each item in the table for _,part in pairs(myTable) do --Only change the brickcolor if it's actually a Part otherwise you may get an error if part:IsA("BasePart") then part.BrickColor = BrickColor.Red() end end end script.Parent.ClickDetector.MouseClick:connect(Colour)