Stamina script is glitchy

You can write your topic however you want, but you need to answer these questions:

Hello guys, I’ve created a simple stamina script and it works fine the first time you use it. (See GIF below)

After a few tries of using it, when you press SHIFT to sprint, the bar gets empty way more quickly than before. (See GIF below)

There’s nothing related to my topic on the DevForum, as far as I’m aware.
Thanks for reading!
Here’s my code

local UIS = game:GetService("UserInputService")
local bar = script.Parent:WaitForChild("TweenBar")
local shiftSpeed = 24
local normalSpeed = 16
local charge = 10
local sprinting = false
local player = game.Players.LocalPlayer
local humanoid = player.Character:WaitForChild("Humanoid")


UIS.InputBegan:connect(function(key, gameProcessed)

	if key.KeyCode == Enum.KeyCode.LeftShift then
		sprinting = true
		
		while true do wait()
			if sprinting and charge>0 then
				humanoid.WalkSpeed = shiftSpeed
				charge = charge-.1
				bar:TweenSize(UDim2.new(charge / 10, 0, 1, 0), 'Out', 'Quint', .1, true)
				
			elseif charge <=0 then
				humanoid.WalkSpeed = normalSpeed
				
			end
			
			
		end
	end
end)


UIS.InputEnded:Connect(function(input, gameProcessed)
	if input.UserInputType == Enum.UserInputType.Keyboard  then
		humanoid.WalkSpeed = normalSpeed
		sprinting = false
	
		while sprinting == false and charge<10 do wait()
			humanoid.WalkSpeed = normalSpeed
			charge = charge+.1
			bar:TweenSize(UDim2.new(charge / 10, 0, 1, 0), 'Out', 'Quint', .1, true)
		end
	end
end)

every time you hit shift, it is starting another while loop.

you could add something simple like this in the while loop.

if not sprinting then
    break
end
2 Likes