This is my 3rd day practicing and learning Lua for a bit and I can finally read and understand what most scripts are doing, at least on a beginner level. I’m still working on writing code on my own and getting used to the syntax through repetition, so I’ve been creating small random projects to practice.
For this one, I made a simple flickering light system for a parking lot light pole. The SpotLights are placed inside the parts like this:
It works, both lights flicker, but I’m trying to make it faster, more chaotic, and less predictable. Even when I adjust the math.random() values, it still seems to flicker at the same slow pace, and both lights sometimes sync up, which kills the effect.
I’d really appreciate some pointers or suggestions from more experienced scripters on how to make the flickering look more random and realistic (like unstable electricity or horror-style lights).
Alrighty, first of all I’d try avoid while true do as it can be fairly unoptimized. RenderStepped or just while task.wait() would work.
Your current issue is;
At the beginning of the script, you are setting the lights to the opposite of their previous value. What’s happening is your if statements are nested under the same loop, and so they run one after the another.
So when your first flicker turns off, it waits for the second flicker to finish it’s task.wait(). So when they both are off, they turn on at the same time at the beginning of the loop.
To fix this, I’d suggest a function to handle each - this also will allow you to add future lights which, I assume you do.
local function StartFlicker(LightInstance : Instance, LightColor : Instance)
while task.wait(math.random(0.005, 1) / 5) do
if LightInstance.Enabled then
LightColor.BrickColor = BrickColor.new("White")
else
LightColor.BrickColor = BrickColor.new("Black")
end
end
end
StartFlicker(LeftLight, LeftLightColor)
StartFlicker(RightLight, RightLightColor)
This uses a function so each light has it’s own loop - instead of having them both under one loop. The function also cleans up the code and stops you from repeating yourself.
If I missed your problem let me know
As well as this, you can use the enabled feature on the light instead of setting the color. So you can just loop the task.wait and do LightInstance.Enabled = not LightInstance.Enabled