Is this code bad for performance?

Hello, just need some advice, is this script bad for performance? I have a lot of these tagged parts btw, like… 30+

local CollectionService = game:GetService("CollectionService")

local GlowPart = CollectionService:GetTagged("GlowPart")

while true do
	wait(0.1)
	if game.Lighting:GetMinutesAfterMidnight() > 6 * 60 then
		for _, TaggedPart in pairs(GlowPart) do
			if TaggedPart:IsA("SurfaceGui") then
				TaggedPart.Enabled = false
			end
		end
	end

	if game.Lighting:GetMinutesAfterMidnight() > 18 * 60 then
		for _, TaggedPart in pairs(GlowPart) do
			if TaggedPart:IsA("SurfaceGui") then
				TaggedPart.Enabled = true
			end
		end
	end
end

Yes, you don’t want to do polling with this. Instead, try using Lighting.LightingChanged. In your code, it would look like this:

local CollectionService = game:GetService("CollectionService")
local GlowPart = CollectionService:GetTagged("GlowPart")
local Lighting = game:GetService("Lighting") -- Use GetService instead of .Lighting

Lighting.LightingChanged:Connect(function()
	if Lighting:GetMinutesAfterMidnight() > 6 * 60 then
		for _, TaggedPart in pairs(GlowPart) do
			if TaggedPart:IsA("SurfaceGui") then
				TaggedPart.Enabled = false
			end
		end
	end

	if Lighting:GetMinutesAfterMidnight() > 18 * 60 then
		for _, TaggedPart in pairs(GlowPart) do
			if TaggedPart:IsA("SurfaceGui") then
				TaggedPart.Enabled = true
			end
		end
	end
end)

This would only run when lighting changes, instead of every tenth of a second.

1 Like

I don’t reccommend using a while loop with a small wait time, only because of how inaccurate wait can get. Also, why use a while loop when you can just detect a change in ClockTime

I’ve created a toggleLights function which toggles the lights to the specific state

local Lighting = game:GetService("Lighting")

function toggleLights(toggle)
    for _, TaggedPart in pairs(GlowPart) do
	    if TaggedPart:IsA("SurfaceGui") then
		    TaggedPart.Enabled = toggle
	    end
    end
end

local toChange = { -- This tells when to change the lights and how to change them
  [6] = false,
  [18] = true
}

Lighting:GetPropertyChangedSignal("ClockTime"):Connect(function()
    for clockTime, toggleState in pairs(toChange) do
        -- For every loop, clockTime will be the time (6, 18, ...)
        -- For every loop, toggleState will be the state to turn the lights to (true/on, false/off, ...)
        if Lighting.ClockTime > clockTime then
            toggleLights(toggleState)
        end
    end
end)
2 Likes

You guys are geniuses, thankyou so much!

No problem! If it doesn’t work let me know