How can I do while loops with collectionService?

I’m trying to create a while loop light flicker using multiple light sources with collectionService
but it isn’t working and only targets one light even though the tagged shows there is multiple selected?
I have tried putting it in a separate script and that did not work, Is there something wrong or can it not do for loops?

code:

local collectionService = game:GetService(“CollectionService”)

local lights = collectionService:GetTagged(“ceilingLights”)

for i, v in pairs(lights) do

while true do
	v.SurfaceLight.Enabled = true
	task.wait(1)
	v.SurfaceLight.Enabled = false
end

end

There is no error logs as far as I am aware of.

2 Likes

Hmm, I believe your problem is that you are trying to start a while loop for each light, and since the while loop is infinite, it yields and never moves to the next light in the array. In order to do what you want, you should task.defer() each while loop, so it doesn’t yield:


local collectionService = game:GetService(“CollectionService”)

local lights = collectionService:GetTagged(“ceilingLights”)

for i, v in pairs(lights) do
    task.defer(function()
        while true do
	        v.SurfaceLight.Enabled = true
	        task.wait(1)
	        v.SurfaceLight.Enabled = false
            task.wait(1)
        end
    end)
end


Or you could just reverse the order of your loops and do something like this:


local collectionService = game:GetService(“CollectionService”)

local lights = collectionService:GetTagged(“ceilingLights”)

while true do
	for i, v in pairs(lights) do
		v.SurfaceLight.Enabled = true
	end

    task.wait(1)

    for i, v in pairs(lights) do
		v.SurfaceLight.Enabled = false
	end
    task.wait(1)
end

Hope this helped :slight_smile:

4 Likes