How to fix server freezing from using 'for in pairs() do'

Hello devs! I’m coding light manager module for my game. But i got bug when server or client freezing for a while. This happening when i run this code:

for i,a in pairs(workspace.FacilityLight:GetChildren()) do --light outage thing
            task.delay(Rand:NextNumber(0.05,0.4),function()
				a.LightPart.PointLight.Brightness/=2
				a.LightPart.Power_O:Play()
				for i,v in pairs(a.Lights:GetChildren()) do
					v.Material="Metal"
				end
				task.wait(Settings.Times.OutageDelayTime)
				for i,v in pairs(a.Lights:GetChildren()) do
					v.Material="Neon"
				end
				a.LightPart.PointLight.Brightness*=2
				if Type then
					if Power==Settings.CurrentUsingPower then
						task.wait(Settings.Times.OutageDelayTime)
						for i,v in pairs(a.Lights:GetChildren()) do
							v.Material="Metal"
						end
						a.LightPart.PointLight.Enabled = false
					end
				end
			end)
end

I tried to fix this somehow but it still appear.
Also i counted how much lights in ‘FacilityLight’ folder, it is 723 lights.

Should i change light manager to only client side or what solution will be helpful?

1 Like

Likely due to the high number of parts to loop through and change.

Attempt this, see if it performs any better.

A good way to handle large amounts of objects is to use CollectionService to apply functionality, ie turning them all on/off.
https://developer.roblox.com/en-us/api-reference/class/CollectionService