When leftshift is spammed, multiple loops are ran. How to fix?

Hi,

I made this sprinting script. The problem is if you SPAM left shift, and you wait till regeneration it goes really really quick. I know the logic issue, but not a fix. Does anyone know how to fix?

--Sprinting & Stamina
local Stamina = 100
local Running = false

UserInputService.InputBegan:Connect(function(Input, GPE)
	if Input.KeyCode == Enum.KeyCode.LeftShift and not GPE then
		if not Running then--Stamina >= 100 and not Running then
			Running = true
			Character.Humanoid.WalkSpeed = 24
			while Stamina > 0 and Running do
				Stamina -= .5
				Player.PlayerGui.SprintUI.StaminaUI.Holder:TweenSize(UDim2.new(Stamina / 100, 0, 1, 0), "Out", "Linear", 0)
				task.wait(.01)
				if Stamina <= 0 then
					Character.Humanoid.WalkSpeed = 16
					script.Sound:Play()
				end
			end
		end
	end
end)

UserInputService.InputEnded:Connect(function(Input, GPE)
	if Input.KeyCode == Enum.KeyCode.LeftShift and not GPE then
		Running = false
		Character.Humanoid.WalkSpeed = 16
		task.wait(2)
		if not Running then
			while Stamina < 100 and not Running do
				Stamina += .25
				Player.PlayerGui.SprintUI.StaminaUI.Holder:TweenSize(UDim2.new(Stamina / 100, 0, 1, 0), "Out", "Linear", 0)
				task.wait()
				if Stamina <= 0 then
					Character.Humanoid.WalkSpeed = 16
				elseif Stamina >= 100 then
					script.Sound:Stop()
					Player.PlayerGui.SprintUI.StaminaUI.Holder.Size = UDim2.new(1,0, 1,0)
				end
			end
		end
	end
end)

This issue is happening because you have embed multiple task.wait()s into a UserInputService function, so what’s happening is a new function is being fired every time you press LeftShift (which ignores the previous task.wait()s), so for example if you press LeftShift 5 times really fast it will fire the regeneration function 5 times at once except they all mess with the same variable.

You can fix this issue by creating the actual stamina function outside of the UIS functions, only use task.wait(2) outside of UIS.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.