So I'm making a dance floor, and I want the colors on the dance floor to change every few seconds. I used a for loop to access all the parts inside my dance floor, and then inside the for loop I put in a while loop to constantly change the dance floor's color.
Here is the script I used:
for i,parts in pairs(script.Parent:GetChildren()) do if parts.Name == "DanceFloorPart" then parts.Material = "Neon" while true do parts.BrickColor = BrickColor.Random() wait(3) end end end
Now when I run the only one of the parts inside the dance floor change color. Any idea what I did wrong and how to make this work?
By the way, I have this script inside the dance floor, as you probably could tell
If you can help, thank you, and if not, still thank you for your time.
The problem is that in the for loop, it goes through everything in the table that you are looping through in order. So, when it loops for the first element in the table, it runs a while loop. While loops cannot be stopped unless the condition is false OR you 'break' them. This is what is preventing the for loop from continuing, and there is a very easy solution to this.
The solution is to use a while loop, but instead have the for loop inside the while loop, if this doesn't make sense, look at the example code below:
while true do for i, parts in pairs(script.Parent:GetChildren()) do parts.Material = Enum.Material.Neon parts.BrickColor = BrickColor.Random() end wait(3) end
Hi, I'm BlackOrange here to help!
First off, this will only run once. So instead put the while true do loop outside
.
Secondly, script.Parent:GetChildren() can change at any time so might as well loop through those.
Another thing you should do is probably check what object this is or if the object exists. Lot's of times you will find yourself getting nil
Lastly, if your not going to use the index just use _
Here:
while true do wait(3) for _, Children in pairs(script.Parent:GetChildren()) do if Children and Children:IsA('Part') or Children:IsA('MeshPart') then if Children.Name == 'DanceFloorPart' then Children.Material = Enum.Material.Neon -- Use Enum Children.BrickColor = BrickColor.Random() end end end end)
That's improve! Best of luck!
Use spawn()
to run multiple while loops at once
for i,parts in pairs(script.Parent:GetChildren()) do if parts.Name == "DanceFloorPart" then parts.Material = "Neon" spawn(function() while true do parts.BrickColor = BrickColor.Random() wait(3) end end) end end