I'm trying to make the lights of a building flash randomly when you press a button. This is the script I have so far.
function onClick(playerWhoClicked) p = workspace.Buildings.BuildingLights1:GetChildren() for i = 1, #p do wait(math.random(.2,2)) p[i].Color = Color3.fromRGB(0,0,0) wait(math.random(.2,2)) p[i].Color = Color3.fromRGB(255,255,255) end end script.Parent.ClickDetector.MouseClick:connect(onClick)
The script runs, but instead of all the windows flashing at random times, only one window flashes at a time. Is there any way to fix this, besides inserting a script into each window and having the button enable/disable them?
I will take a whack at this; try this code instead:
math.randomseed(os.time()); local function WarmUp() math.random(); math.random(); math.random(); end local function onClick(playerWhoClicked) p = workspace.Buildings.BuildingLights1:GetChildren() for i = 1, #p do spawn(function() WarmUp(); wait(math.random(20, 200) / 100); p[i].Color = Color3.fromRGB(0,0,0) WarmUp(); wait(math.random(20, 200) / 100); p[i].Color = Color3.fromRGB(255,255,255) end) end end script.Parent.ClickDetector.MouseClick:connect(onClick)
Now let me explain...
The WarmUp function is called so that we can 'warm up' Lua's pseudo random number generator so that we will actually get a random result when we call math.random.
WarmUp();
math.randomseed will set the seed of the pseudo random number generator to its argument; again this helps us generate more 'randomized' numbers
math.randomseed(os.time());
we spawn a function to create a new thread (i.e. kind of like creating a new script) that can execute the code inside of it without stalling our main script, therefore our main script can continue executing the for loop, and your lights will flicker on and off all around the same time.
spawn(function() ... end);
Finally, if you REALLY want random numbers in between 0.2 and 20, then you should call math.random with the arguments 20, and 200, then divide the result by 100 to get a random integer between 0.2 and 20.
local wait_time = math.random(20, 200) / 100;
I hope this helps you.