How can I make these lights turn on one after another in a random order?

I’ve been trying to look for a way to make these lights can turn on one by one, but in a random order.
Any help would be appreciated.

local lights = game.Workspace.lights
for i, v in pairs(lights:GetDescendants()) do
		if v:IsA("SurfaceLight") then
			v.Enabled = true
		end
	end

One option I can think of is to put the lights into a table, like lights:GetDescendants, then shuffle it, like using this code here:

Probably use a task.wait(math.random(0.2,0.7)) to get a nice delay in between (feel free to change the values) and you have a randomized list!

1 Like

Add a task.wait() so the lights don’t turn on all at the same time.

local lights = game.Workspace.lights
local Time = 1 -- seconds it takes to turn on the next light

for i, v in pairs(lights:GetDescendants()) do
		if v:IsA("SurfaceLight") then
			v.Enabled = true
		end
        task.wait(Time)
	end

As for random order, use tables as suggested above.

1 Like

Here’s how to implement the Fisher-Yates shuffle, lmk if you have any questions about understanding how the code works!

local function shuffleTable(t)
    for i = #t, 2, -1 do
        local j = math.random(i)
        t[i], t[j] = t[j], t[i] 
    end
end

local lights = {}
for i, v in pairs(game.Workspace.lights:GetDescendants()) do
    if v:IsA("SurfaceLight") then
        table.insert(lights, v)
    end
end

shuffleTable(lights)

for i, light in ipairs(lights) do
    task.wait(1) -- however long you want
    light.Enabled = true
end
1 Like

Thanks, I’m finally able to do it

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.