The Problem
Hi there! I just made a system that flicker lights. All of the lights are stored in 1 folder and I got them from the folder using for i,v in pairs. The problem is that it doesn’t change all of the lights at the same time, but first one light and then another light, but not all of the lights on the same time.
The Code: I used a localscript for this code.
-- Variables
local flickeringLights = game.Workspace:WaitForChild("FlickeringLights")
-- Core Script
while wait() do
for i,v in pairs(flickeringLights:GetChildren()) do
v.Light.Brightness = 10
v.Material = Enum.Material.Neon
wait(1)
v.Light.Brightness = 0
v.Material = Enum.Material.SmoothPlastic
wait(0.3)
v.Light.Brightness = 10
v.Material = Enum.Material.Neon
wait(0.5)
v.Light.Brightness = 0
v.Material = Enum.Material.SmoothPlastic
wait(0.8)
end
end
(also faster and recommended in this case, no idea why pairs is being used)
you also added a wait() so the lights aren’t going to change state at the same time
That is because you have coded it to “wait” several times per every-single-light you iterate through. The same as incapaz points to, but then suggest a not-very-good alternative using coroutines (it would need at least a wait(1 + 0.3 + 0.5 + 0.8) per every while iteration.)
To “fix” that, you instead need to “wait” after the for-loop. So you would need to make multiple for-loops:
while true do
-- Set all lights to brightness 10, material Neon
for i,v in ipairs(flickeringLights:GetChildren()) do
v.Light.Brightness = 10
v.Material = Enum.Material.Neon
end
-- Wait one second
wait(1)
-- Set all lights to brightness zero, material SmoothPlastic
for i,v in ipairs(flickeringLights:GetChildren()) do
v.Light.Brightness = 0
v.Material = Enum.Material.SmoothPlastic
end
-- Wait 0.3 second
wait(0.3)
-- etc.
end
As you probably don’t want to repeat all those for-loops again and again, then you can look into using functions with arguments:
local function SetAllLightsTo(brightness, material)
-- Set all lights to the brightness and material, given as arguments to this function
for i,v in ipairs(flickeringLights:GetChildren()) do
v.Light.Brightness = brightness
v.Material = material
end
end
while true do
SetAllLightsTo(10, Enum.Material.Neon)
wait(1)
SetAllLightsTo(0, Enum.Material.SmoothPlastic)
wait(0.3)
-- etc.
end