Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How would I get all parts instead of one by one with a for loop?

Asked by 7 years ago

I just need to know if I can get ALL the lights instead of one by one on that for loop?

Overall, what I want to do is for the script to choose a random color from the color values I have in a folder in the same parent as script and get ALL the lights to have that same color. This script works but all the parts get different colors.

-- Sodaghost13

local light = script.Parent:GetChildren()
local colorsfolder = script.Parent.ColorsFolder:GetChildren()

for i = 1, #light do
    if light[i].Name == "Light" then
        local ChosenColor = colorsfolder[math.random(1, #colorsfolder)]
        GetColor = ChosenColor.Value
        light[i].Color = GetColor
    end
end
1
Just move line 8 outside of the for loop, before the loop. M39a9am3R 3210 — 7y
0
That seems like the perfect code I don't see nothing wrong! rustyhuskey 59 — 7y

1 answer

Log in to vote
0
Answered by 7 years ago

You made the script so it changes the light color randomly because of the looped code in line 8. Move it outside of the for loop. Also, when iterating over stuff, you can use pairs or ipairs to do so instead of a numeric for loop, but that's still okay.

Here is the code:

-- Sodaghost13

local light = script.Parent:GetChildren()
local colorsfolder = script.Parent.ColorsFolder:GetChildren()
local ChosenColor = colorsfolder[math.random(1, #colorsfolder)] -- Moved from line 8 of your original code.

for _, v in ipairs(light) do -- Not really necessary, but it's useful as well.
    if v.Name == "Light" then
        GetColor = ChosenColor.Value
        v.Color = GetColor
    end
end

Any questions? Please leave a comment below. Thanks! :)

Ad

Answer this question