For do loop does not get all children of a model

This is my second post. I am wondering how and why it only gets 1 children.

I wanted to use for do loop in my script, then use while true do so it loops through
all children forever

What I’m trying to do is to switch to a BrickColor, then switch to a BrickColor again
every 0.5 seconds

Script:

local children = script.Parent.Parent:GetChildren()

for _, child in ipairs(children) do
	while true do
		child.BrickColor = BrickColor.new("Bright red")
		wait(0.5)
		child.BrickColor = BrickColor.new("Maroon")
		wait(0.5)
	end
end

Gameplay test:


Any help?

1 Like

It just won’t proceed to the next child because your loop has code that will yield infinitely, not proceeding to the next child. You have to use a coroutine or task.spawn.

1 Like

Seems like you should flip your for loop and while loop, it’d be better for performance and work better. You’ll also need task.spawn() to get everything on a separate thread, which will prevent it from going 1 part at a time.

while true do
    for _, child in ipairs(script.Parent.Parent:GetChildren()) do
        task.spawn(function())
		    child.BrickColor = BrickColor.new("Bright red")
		    wait(0.5)
		    child.BrickColor = BrickColor.new("Maroon")
		    wait(0.5)
        end
	end
end
2 Likes

@KdudeDev and @7z99

I will try that and continue to learn what task.spawn is

1 Like