How can I optimize this checking system so it doesn't lag?

My game is lagging a bit because I did this function that returns a variable from a local script but i use it in a loop which isn’t very optimized, is there something I can do so the game doesn’t lag anymore? Also I will try to put my functions in a module script but I’m not sure if it will solve the issue.

The function in server sided script:

local function getButtonState(player)
	remoteEvent:FireClient(player, "requestButtonState")
	local player, buttonState = remoteEvent.OnServerEvent:Wait()
	return buttonState
end

The loop:

local function punch(player, side)
	local timer = tick()
	local humanoid = player.Character:FindFirstChild("Humanoid")
	local animator = humanoid:FindFirstChild("Animator")
	local punchAnim = Instance.new("Animation")
	punchAnim.AnimationId = chooseAnimation(punchAnimations, player, side)
	local punchTrack = animator:LoadAnimation(punchAnim)
	punchTrack.Looped = false
	punchTrack:Play()
	sound_swingBack:Play()
	punchTrack:GetMarkerReachedSignal("Guarding"):Wait()
	punchTrack:AdjustSpeed(0)
	while getButtonState(player) == true do  --Here!!
		task.wait()
	end
	punchTrack:AdjustSpeed(1)
	sound_swingForward:Play()
	hitbox(player, (tick() - timer))
	punchTrack.Ended:Wait()
	remoteEvent:FireClient(player,"animEnded")
end

And the local script event:

remoteEvent.OnClientEvent:Connect(function(action)
	if action == "altAnim" then
		altAnim = not altAnim
	elseif action == "animEnded" then
		canAct = true
	elseif action == "requestButtonState" then
		remoteEvent:FireServer(keyPressed)  --Here!!
	end
end)

Thanks for any help!! :))

1 Like

Maybe just remove the task.wait()? If you have the :Wait() already in the function that’s being called, it should still yield so that the loop doesn’t crash. Essentially, keep the condition of your while loop the same, but just make the body of the loop empty.

1 Like

I don’t know if it optimized but it definitely worked so thank you!!

1 Like

I would suggest you play animation on the client side because it will be replicated to the server anyways.

Also, I think that you should check in your other scripts to see if there are memory leaks so it will optimize the game and prevent game from crashing when players are playing the game.

No problem, if it did help though, I would recommend marking my answer as the solution by clicking the ‘Solution’ button below it. It will help other people who are having the same issue quickly find the solution.

1 Like