My stamina script keeps crashing

I want the script to decrease the stamina bar while the player’s speed is bigger than 4, and increase the stamina bar if the player’s speed is less or equal to 4. This works but when I stop moving the stamina bar still moves slowly and when it hits 0 the whole game crashes. How do I fix this?

local UIS = game:GetService('UserInputService')

local Bar = script.Parent:WaitForChild('Background'):WaitForChild('Bar')

local player = game.Players.LocalPlayer

local NormalWalkSpeed = 4
local NewWalkSpeed = 20

local power = 10

local sprinting = false

repeat wait() until game.Players.LocalPlayer.Character

local character = player.Character

--= Functions =--

character.Humanoid.Running:Connect(function(speed)
    if power > 0 then
        while speed > 4 do
            if power > 0 then
                power = power - .03
                Bar:TweenSize(UDim2.new(power / 10, 0, 1, 0), 'Out', 'Quint', .1, true)
                Bar.BackgroundColor3 = Bar.BackgroundColor3:lerp(Color3.fromRGB(255, 42, 42), 0.001)
                wait()
            end
        end
        while speed <= 4 do
            if power < 10 then
                power = power + .03
                Bar.BackgroundColor3 = Bar.BackgroundColor3:lerp(Color3.fromRGB(255, 166, 11), 0.001)
                Bar:TweenSize(UDim2.new(power / 10, 0, 1, 0), 'Out', 'Quint', .1, true)
                wait()
            end
        end
    else
        character.Humanoid.WalkSpeed = 4
    end
end)

why is wait() inside the if statement, It will crash studio

character.Humanoid.Running:Connect(function(speed)
	if power > 0 then
		while speed > 4 do
			if power > 0 then
				power = power - .03
				Bar:TweenSize(UDim2.new(power / 10, 0, 1, 0), 'Out', 'Quint', .1, true)
				Bar.BackgroundColor3 = Bar.BackgroundColor3:lerp(Color3.fromRGB(255, 42, 42), 0.001)
			end
			
			wait()
		end
		while speed <= 4 do
			if power < 10 then
				power = power + .03
				Bar.BackgroundColor3 = Bar.BackgroundColor3:lerp(Color3.fromRGB(255, 166, 11), 0.001)
				Bar:TweenSize(UDim2.new(power / 10, 0, 1, 0), 'Out', 'Quint', .1, true)
			end
			
			wait()
		end
	else
		character.Humanoid.WalkSpeed = 4
	end
end)
2 Likes