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

How to stop while loop by releasing key?

It's supposed to charge the users mana, and it does, but it doesn't stop when release the key. I have to wait until the mana reaches 100, and then I have to press the key again to stop it. How can I make it so that it stops charging when I release the key? I figure it's supposed to be like the opposite of a stamina bar used for sprinting, but I still couldn't get it to work.


m = game.Players.LocalPlayer:GetMouse() -- Charging
m.KeyDown:connect(function(key)
	if key == "f" then 
        while Player.Character.Humanoid.Mana.Value < 100   do
		game.Players.LocalPlayer.Character.Humanoid.Mana.Value = 		game.Players.LocalPlayer.Character.Humanoid.Mana.Value + 1
        wait(0.01)
		end
	end
end)
		
m.KeyUp:connect(function(key) -- Stop charging
	if key == "f" then
		game.Players.LocalPlayer.Character.Humanoid.Mana.Value = game.Players.LocalPlayer.Character.Humanoid.Mana.Value + 0
	end
end)



3 comments

0

I recomend using one variable, that gets enabled when pressed, disabled when released, then using a while wait loop with an if statement that checks the variable

0

btw, keydown is deprecated, use userinputservice

0

Thanks, I watched a tutorial on UIS, and I did what you said and it's working fine.

1 answer

uis = game:GetService("UserInputService")


uis.InputBegan:connect(function(input)
	if input.KeyCode == Enum.KeyCode.E then
        charging = true
		while charging == true do
		game.Players.LocalPlayer.Character.Humanoid.Mana.Value = game.Players.LocalPlayer.Character.Humanoid.Mana.Value	 + 1 
	    wait() 
        if charging == false then return end
        if game.Players.LocalPlayer.Character.Humanoid.Mana.Value == 100 then return end
     	end
	end	
end)

uis.InputEnded:connect(function(input)
		if input.KeyCode == Enum.KeyCode.E then
    	charging = false
	end
end)

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