Would using this loop cause too much lag for the client? [RESOLVED]

So i have to detect if the player attempts to move (not whenever they are moving as they cannot move when hiding) whenever the hiding attribute is set to true, and i have already achieved that, however, im not sure if this will create lag. Will this cause too much lag? And if so, how can i fix it?

local userInputService = game:GetService("UserInputService")

local remoteEvents = game:GetService("ReplicatedStorage").RemoteEvents

local exitLockerEvent = remoteEvents.ExitLockerEvent

local Player = game:GetService("Players").LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:FindFirstChild("Humanoid")

if not Humanoid then
	return
end

while task.wait() do
	if Character:GetAttribute("Hiding") == true then
		if Humanoid.MoveDirection.Magnitude > 0 then
			print("hi")
			exitLockerEvent:FireServer(Player)
		end
	end
end

Edit: It is causing severe lag, how do i fix this???

2 Likes

just a quick thing I think this might need to be in scripting support because you also need help in for the lag issue

only thing I could think of is to wrap into a task.spawn() so like

task.spawn(function()
while task.wait() do
	if Character:GetAttribute("Hiding") == true then
		if Humanoid.MoveDirection.Magnitude > 0 then
			print("hi")
			exitLockerEvent:FireServer(Player)
		end
	end
end
end)

likely, since you’re using geattribute every frame. potentially, you could do

local userInputService = game:GetService("UserInputService")

local remoteEvents = game:GetService("ReplicatedStorage").RemoteEvents

local exitLockerEvent = remoteEvents.ExitLockerEvent

local Player = game:GetService("Players").LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:FindFirstChild("Humanoid")

if not Humanoid then
	return
end

Character:GetAttributeChangedSignal("Hiding"):Connect(function()
        -- use your stuff here, idk
end)

look into guard clauses btw, instead of

if not SomeValue then -- not the value, so we do something
   Something()
end

do

if SomeValue then return end -- its the value, so do not continue. warning! in loops where you want them to run even if the condition is/isn't the state you want, use continue over return

Something()
1 Like

looping that much might just lag, try using the changed functions like @Firefighter_1234567 mentioned

Hi! This works since the code isnt running until the player hides, however after the player stops hiding, the code is still running, would there be a way to stop this?

Nevermind! I added onto your code so that it returns end if its false, and now the loop only runs whenever the player is hiding! Thank you all for your time!

1 Like

yes, just do some if checks, wayy easier than constant while true. happy coding