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

What am I doing wrong with this ipairs function?

Asked by 8 years ago
wait(10)
for _, part in ipairs(script.Parent:GetChildren()) do
    while wait(2) do
    part.BrickColor = BrickColor.Random()
    end
end

So what I am doing is making a dance floor, but when I run this script it only changes one part instead of all of them. And I don't know what I am doing wrong. Any Help is appreciated :)

1 answer

Log in to vote
3
Answered by
Unclear 1776 Moderation Voter
8 years ago

The problem lies in the following line...

while wait(2) do

wait is a function that returns a few results (what they are isn't relevant). The point is, it will always be a true statement, and therefore your loop will run forever. This means that after it tries to start changing one part's color, naturally it will not move on to changing another part's color because the while loop's statement will always be true.

I am guessing you just want the colors to change every 2 seconds, so this is just a matter of you not putting them in the right order.

The idea is that a loop is applied upon its contents. Whatever is inside of the loop is what gets looped. Instead of looping through all of the children and then continuously looping every 2 seconds to change parts until wait returns false (which it never will because of the logic above), we will loop every 2 seconds and then change all of the colors of the parts!

Here is what that would look like...

wait(10)
while wait(2) do
    for _, part in ipairs(script.Parent:GetChildren()) do
        if part:IsA("BasePart") then -- Be sure to make sure you are only trying to change colors of things that are BaseParts... will throw an error if you try to edit something like this Script
                part.BrickColor = BrickColor.Random()
        end 
    end
end
0
You could prolly use coroutines to make the original code work, but I can't think of a reason why you'd do that. funyun 958 — 8y
Ad

Answer this question