i’m making a stamina system, stamina has its value and so on
now i want stamina to regenerate after 2 seconds after an action, until it reaches max or gets interrupted by another action
that’s going very horribly
i’m no longer using this, but this is the only thing i’ve tried as i have no other ideas
Stamina.Changed:Connect(function()
-- there was a statement that checked if the stamina went down, i don't remember it
task.wait(2)
repeat
task.wait(0.050)
Stamina.Value += 1
StaminaGUI.Text = Stamina.Value
until Stamina.Value == 100 or -- action is performed
end)
that very much didn’t work, it would endlessly add 1 to the stamina and would never stop, getting to high numbers and crashing studio
You’d want to have a while loop run after you start sprinting and after you stop sprinting. One’s purpose will be for decreasing stamina, that is whenever you start sprinting, and one’s purpose is to increase stamina; this will be for when you stop sprinting. I’d suggest having 3 booleans; increasing stamina, decreasing stamina and sprinting. So you can do the accordingly checks on those while loops and if as example the user is not sprinting you break out of the loop and do the according checks if the stamina is as example above 100 then break end. Think a bit through it by a logical manner
So you would not have a while loop for decreasing the stamina, you script it that way that it gets instantly decreased from that amount. The only difference would be is that you would not need a variable for decreasingStamina and no while loop is required for that. That makes it easier in this case
Let’s give a little bit of a demonstration what you could do;
local function increaseStamina(waitTime, increaseAmount)
while true do
if yourValue >= 100 then break end
yourValue += increaseAmount
task.wait(waitTime)
end
Just something very simple that you can reference it of
local Regenerating = false
Stamina.Changed:Connect(function(Value)
--Regenerating = false Something something to make this false, like a jump.
task.delay(2,function()
if Value == Stamina.Value then
Regenerating = true
while Regenerating do
Stamina.Value = math.clamp(Stamina.Value + 1, 0, 100) -- 100 is maximum stamina
task.wait(0.2)
end
end
end)
end)
Don’t use repeat to set a value to a maximum number, use math.clamp instead. oOr tweens if you’re scary.
My method is that create a timer variable then get Runservice.Heartbeat with delta time. If the timer is smaller than coolDown or the stamina not is maxed, Make the timer +=deltaTime
When the timer>=cooldown, increase the stamina
When the action event triggered set the timer to 0 again.