Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I keep it from repeatedly regenerating?

This is the code for a stamina bar in my game. It is supposed to regenerate after the player either runs out of stamina, or stops sprinting. It keeps regenerating while sprinting though. It is in a LocalScript under the StarterGui.

local StaminaBar = script.Parent
local Stamina = StaminaBar:WaitForChild("Stamina")
local Frame = StaminaBar.Parent
local Warning = Frame:WaitForChild("Warning")
local InputService = game:GetService("UserInputService")
local Player = game.Players.LocalPlayer
local Keys = {}

InputService.InputBegan:connect(function(Input)
	Keys[Input.KeyCode.Name] = true
	while Keys.Q and Stamina.Value > 0 do
		Player.Character.Humanoid.WalkSpeed = 28
		wait(0.01)
		Stamina.Value = Stamina.Value - 1
		StaminaBar.Size = StaminaBar.Size - UDim2.new(0.01, 0, 0, 0)
	end
end)
	
InputService.InputEnded:connect(function(Input)
	Keys[Input.KeyCode.Name] = false
	if not Keys.Q then
		Player.Character.Humanoid.WalkSpeed = 16
		wait(4)
		Warning:TweenPosition(UDim2.new(0.2, 0, 0, 0), "Out", "Quad", 0.25, true, nil)
		StaminaBar:TweenSize(UDim2.new(1, 0, 1, 0), "Out", "Quad", 0.5, true, nil)
		Stamina.Value = 100
	end
end)

Stamina.Changed:connect(function()
	if Stamina.Value < 40 then
		Warning:TweenPosition(UDim2.new(0.2, 0, -1.3, 0), "Out", "Quad", 0.25, true, nil)
	end
end)

1 answer

✓ Accepted answer

The problem is that you tell it to always regenerate to full in your InputEnded event. You should use the same algorithm as your InputBegan (use a while loop). If you do this, you'll also want to extend your if statement in your Stamina Changed function so that your Warning object will automatically hide itself at the proper time.

This discussion is preserved as it was. New answers, comments, and votes are closed.