My Stamina system does not work and I can not figure out why

I want to make a Stamina system, where you can when pressing shift run until you run out of breath and then regenrate when you are not pressing shift

The IntValue is not changing or reducing so I can forever and even if I have -100 stamina,even though the GUI works fine and the sprinting too.

My code:
local Player = game:GetService(“Players”).LocalPlayer
local Character = Player.Character
local Camera = game.Workspace.CurrentCamera
local UserInputService = game:GetService(“UserInputService”)
local TweenService = game:GetService(“TweenService”)
local Stamina = script.Parent:WaitForChild(“Stamina”)
local ShiftPressed = false

-- For making a zoomy effect
function TweenTheZooom(goal) 
    TweenService:Create(workspace.CurrentCamera, TweenInfo.new(1), {FieldOfView = goal}):Play()
end


if Stamina.Value >= 0 then
	while true do 
		--//Shift Pressed
		UserInputService.InputBegan:Connect(function(key)
			if key.KeyCode == Enum.KeyCode.LeftShift then
				Character.Humanoid.WalkSpeed = 32
				TweenTheZooom(80)
				ShiftPressed = true
			end
		end)
		
		while ShiftPressed == true do
			print("Shift pressed")
			Stamina.Value = Stamina.Value - 2 --This should update the value of it when shift is pressed
			wait(0.2)
		end
		--//Shift lifted
		UserInputService.InputEnded:Connect(function(key)
			if key.KeyCode == Enum.KeyCode.LeftShift then
				Character.Humanoid.WalkSpeed = 16
				TweenTheZooom(70)
			ShiftPressed = false
			end
		end)
		wait()
	end

elseif Stamina.Value <= 100 then
	repeat Stamina.Value = Stamina.Value + 2 wait(0.2)
	until (Stamina.Value == 100)
end

screenshots:
of my index->

of what it looks like in the game->

@SCHADOg21 It should work if you would place the Stamina in ReplicatedStorage, most probably and access it like this:

local Stamina = game:GetService("ReplicatedStorage"):WaitForChild("Stamina")
1 Like

Great it works now, got some problems with it overflowing (going into the negatives because it keeps reducing) because of bad if statement, how to fix? @WaterJamesPlough

You can use the math.clamp function to restrict a number’s lowest and highest value. Example:

local Number = 1
Number = math.clamp(Number - 2, 0, 100)
print(Number) --// 0 (clamped to minimum value) 

math.clamp takes three arguments: value, min, and max. If value goes below min, then it will be clamped to min. Same goes for max.

2 Likes