Problem with CollectionService

Hey, so I’m doing a StreetLight CollectionService script, but as it is a loop, it doesn’t check the rest of the street lights. How could I fix this?

local CollectionService = game:GetService("CollectionService")
local TaggedLight = CollectionService:GetTagged("StreetLights")

for i, Light in pairs(TaggedLight) do
	print("one")
	local lightPart = Light.SpotLight
	while true do
		wait(0.1)
		if game.Lighting:GetMinutesAfterMidnight() == 6 * 60 then
			lightPart.Brightness = 1
			wait(0.05)
			lightPart.Brightness = 0.9
			wait(0.05)
			lightPart.Brightness = 0.7
			wait(0.05)
			lightPart.Brightness = 0.9
			wait(0.05)
			lightPart.Brightness = 0.6
			wait(0.05)
			lightPart.Brightness = 0.5
			wait(0.05)
			lightPart.Brightness = 0.4
			wait(0.05)
			lightPart.Brightness = 0.5
			wait(0.05)
			lightPart.Brightness = 0.5
			wait(0.05)
			lightPart.Brightness = 0.6
			wait(0.05)
			lightPart.Brightness = 0.3
			wait(0.05)
			lightPart.Brightness = 0.2
			wait(0.05)
			lightPart.Brightness = 0.1
			wait(0.05)
			lightPart.Brightness = 0
			print("yh")
		end
		if game.Lighting:GetMinutesAfterMidnight() == 18 * 60 then
			lightPart.Brightness = 0
			wait(0.05)
			lightPart.Brightness = 0.1
			wait(0.05)
			lightPart.Brightness = 0.2
			wait(0.05)
			lightPart.Brightness = 0.3
			wait(0.05)
			lightPart.Brightness = 0.6
			wait(0.05)
			lightPart.Brightness = 0.5
			wait(0.05)
			lightPart.Brightness = 0.5
			wait(0.05)
			lightPart.Brightness = 0.4
			wait(0.05)
			lightPart.Brightness = 0.5
			wait(0.05)
			lightPart.Brightness = 0.6
			wait(0.05)
			lightPart.Brightness = 0.9
			wait(0.05)
			lightPart.Brightness = 0.7
			wait(0.05)
			lightPart.Brightness = 0.9
			wait(0.05)
			lightPart.Brightness = 1
		end
	end
end
1 Like

You can wrap the hole loop around a coroutine:

coroutine.create(function()
    -- while loop here
end)()

This is because Lisa is single threaded and therefor needs the previous line to finish executing before the next like executes. Coroutines more or less creates another thread.

1 Like

coroutine.create returns a Thread datatype which can only be ran with coroutine.resume.

You’re looking to use coroutine.wrap which returns a function you can call.

More on Coroutines:

2 Likes