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

Need help with activating a function while I'm hold a key down?

I'm trying to move a part forward while I'm HOLDING a key W. When I release button W then part shouldn't go forward. How could I possibly do it? Please help me

1 answer

✓ Accepted answer

To run a function while holding a key you'll want to use the repeat loop and a simple boolean variable. Doing this, once you start holding the key, the loop will run until you stop holding the key. As seen here:

local holdingW = false
local userInputService = game:GetService("UserInputService")

userInputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.W then
		holdingW = true -- Being loop:

		repeat
			wait(0.2)
			print("Is holding W")
		until holdingW == false
	end
end)

userInputService.InputEnded:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.W then
		holdingW = false -- End loop.
	end
end)

As you can see the loop will run until it detects a change within the variable. Even when made outside of the loop.

3 comments

0

Omg it worked. Thank you

0

Welcome bro

0

nice answer

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