I am trying to make a horror game with a stamina and sprinting system. However, I noticed that after you sprint once, sprinting again causes your stamina bar to go down twice as fast–and regenerate twice as fast. Here is my code which is inside StarterCharacterScripts.
local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local CV = Character.CharacterValues
local Humanoid = Character:FindFirstChildOfClass("Humanoid")
local RunningSpeed = 32
local CurrentStamina = CV.Stamina
local Sprinting = CV.Sprinting
Humanoid:GetPropertyChangedSignal("WalkSpeed"):Connect(function()
while true do
task.wait(1)
if Sprinting.Value == true and CurrentStamina.Value > 0 then
CurrentStamina.Value -= 4
elseif not (Sprinting.Value == true) and CurrentStamina.Value < 100 then
CurrentStamina.Value += 1
end
end
end)
while true do
task.wait()
if CurrentStamina.Value < 0 then
while CurrentStamina.Value < 0 do
CurrentStamina.Value += 1
end
end
end
Humanoid:GetPropertyChangedSignal("WalkSpeed"):Connect(function()
task.spawn(function()
while true do
task.wait(1)
if Sprinting.Value == true and CurrentStamina.Value > 0 then
CurrentStamina.Value -= 4
elseif not (Sprinting.Value == true) and CurrentStamina.Value < 100 then
CurrentStamina.Value += 1
end
end
end)
end)
repeat with the other one.
EDIT:
I don’t think the other while loop is necessary, I would try to remove it, I also added type checking to your version:
local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local CV = Character.CharacterValues
local Humanoid = Character:FindFirstChildOfClass("Humanoid")
local RunningSpeed = 32
local CurrentStamina = CV.Stamina
local Sprinting = CV.Sprinting
task.spawn(function()
while true do
task.wait(1)
if Sprinting.Value and CurrentStamina.Value > 0 then
CurrentStamina.Value -= 4
elseif not Sprinting.Value and CurrentStamina.Value < 100 then
CurrentStamina.Value += 1
end
-- Ensure stamina doesn't go below 0
if CurrentStamina.Value < 0 then
CurrentStamina.Value = 0
end
end
end)
local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local CV = Character.CharacterValues
local Humanoid = Character:FindFirstChildOfClass("Humanoid")
local RunningSpeed = 32
local CurrentStamina = CV.Stamina
local Sprinting = CV.Sprinting
while true do
task.wait(1)
if Sprinting.Value == true and CurrentStamina.Value > 0 then
CurrentStamina.Value -= 4
elseif not (Sprinting.Value == true) and CurrentStamina.Value < 100 then
CurrentStamina.Value += 1
end
end
you are making a new while loop everytime the property “Walkspeed” is changed, so everytime you run, or change back to walk, it will make new loops thus every loop adds additional stamina.