Help with stamina

I wrote a stamina script, however the main problem is the amount of performance it uses. When I comment out the loop, the performance halves, from 44.0/s to 20.0/s which is half. I looked into this when one of the testers couldn’t play because of the extreme lag, even me with a good PC lags slightly.

However, I have no idea how to make a stamina system without a loop, is it possible?

Script:

coroutine.wrap(function()
	while wait() do
		if humanoid.WalkSpeed < 1 then staminaBar.Parent.Visible = false continue end
		if humanoid.MoveDirection ~= Vector3.new(0,0,0) then
			if HOLDING_SHIFT then
				if stamina > 0 then
					stamina = stamina - 1
				end
			end
		else
			runAnim:Stop()
			humanoid.WalkSpeed = 16
		end
		if stamina < 1 then
			runAnim:Stop()
			humanoid.WalkSpeed = 16
		end
		if stamina < 100 and not HOLDING_SHIFT then
			stamina = stamina + 0.5
		elseif stamina >= 100 then
			staminaBar.Parent.Visible = false
		end
		staminaBar.Size = UDim2.new(stamina/100,0,1,0)
	end
end)()

local function handleInput(actionName, inputState, inputObject)
	if actionName == "Sprint" then
		if humanoid.WalkSpeed < 1 then return end
		if inputState == Enum.UserInputState.Begin then
			HOLDING_SHIFT = true
			if stamina > 0 then
				staminaBar.Parent.Visible = true
				humanoid.WalkSpeed = 25
				runAnim:Play()
				runAnim:AdjustSpeed(1.6)
			else
				humanoid.WalkSpeed = 16
				runAnim:Stop()
			end
		else
			HOLDING_SHIFT = false
			humanoid.WalkSpeed = 16
			runAnim:Stop()
		end
	end
end

Thanks!

1 Like

Here’s a great YouTube tutorial.

2 Likes

You can make a sprint stamina in a local script, only with keybinds functions without loop

1 Like

Edit: I just shared my sprint stamina system in community Ressources, it is without a infinity loop

1 Like