Making a stamina system

Ah, I would’ve included a regenerate stamina but you didn’t have it in your original post, thought it was a one time thing.

local Stamina = 100

local SprintHeld = false
local Sprinting = false
local Exhausted = false

local RunRefresh = 20 -- when to allow running after exhausted
local SpeedDiff = 6
local DrainRate = 20 -- drain per second

local function sprint(active)
	if Exhausted then return end -- we can't run because we're exhausted!
	if active then
		Humanoid.WalkSpeed = Humanoid.WalkSpeed + SpeedDiff
	else
		Humanoid.WalkSpeed = Humanoid.WalkSpeed - SpeedDiff
	end
	Sprinting = active
end

UserInputService.InputBegan:Connect(function(input)
    if input.KeyCode ~= Enum.KeyCode.LeftShift or input.KeyCode == Enum.KeyCode.ButtonR2 then return end
	SprintHeld = true
	sprint(SprintHeld)
end)

UserInputService.InputEnded:Connect(function(input)
    if input.KeyCode ~= Enum.KeyCode.LeftShift or input.KeyCode == Enum.KeyCode.ButtonR2 then return end
	SprintHeld = false
	sprint(SprintHeld)
end)

RunService.Heartbeat:Connect(function(DeltaTime)
	if Sprinting then
		if Stamina > 0 then
			Stamina = Stamina - DrainRate * DeltaTime
		else
			sprint(false)
			Exhausted = true
		end
	elseif Stamina < 100 then
		Stamina = Stamina + DrainRate * DeltaTime
		if Stamina > RunRefresh then -- we can now run again!
			Exhausted = false
			if SprintHeld then -- resume running because player is still holding down the sprint key!
				sprint(SprintHeld)
			end
		end
	end
end)
29 Likes