Stop code running 5000 (literally) times in RenderStepped function

Hello! While trying to make a LocalScript that hides away prompts and info about game passes when far away, I realized that the script created a tremendous amount of lag. Apparently activity was sometimes at 50% when processing only one SurfaceGUI Prompt.

I found the primary issue, whenever the Distance was smaller than 12, even if the SurfaceGUI was already “Visible” (just the debug attribute name I chose), it would still keep running. Up to 5000 times. No, really.

image

local function tweenGUIItems(items, visible) -- broken down to just a print for testing, laggy anyway
	print("alpha")
end
game:GetService("RunService").RenderStepped:Connect(function()
	if currentCharacter ~= nil then
		currentCharacter.Humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(function()
			for _,prompt in pairs(visualPrompts) do
				local Distance = math.floor(player:DistanceFromCharacter(prompt.Position))
                    -- i was hoping that math.floor would help; it didn't.

				if Distance <= 12 and prompt:GetAttribute("Visible") == false then
					prompt:SetAttribute("Visible", true)
					tweenGUIItems(prompt.SurfaceGui:GetChildren(), true)
				elseif prompt:GetAttribute("Visible") == true then
					prompt:SetAttribute("Visible", false)
					tweenGUIItems(prompt.SurfaceGui:GetChildren(), false)
				end
			end
		end)
	end
end)

Can anyone help me understand the problem here? I just don’t see it. Thanks in advance!

RenderStepped event fires every frame, that’s why.

Probably because you’re connecting a new function every single frame.

And yet… It does run a check, which should stop “other” frames besides the one acting from performing anything. and prompt:GetAttribute("Visible") == false then

Even then, what are your proposed alternatives?

Maybe just destroy the Humanoid.MoveDirection function?

currentCharacter.Humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(function() was left in from an old variant of code and I didn’t even notice until now.

Yeah, nested connections are always going to be a bad idea (especially when you don’t disconnect them appropriately), you were essentially creating a connection to the humanoid’s “MoveDirection” property every frame, this means that after 60 frames (typically 1 second) if the humanoid’s “MoveDirection” changed, this event would be fired 60 times.

1 Like