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

Problem with UserInPutService and InputBegan?

Hello there, recently, I've been trying some stuff with UserInputService. I wanted to fire a function while a key is pressed, something like this:

Game:GetService("UserInputService").InputBegan:Connect(function(key)
if key.KeyCode == Enum.KeyCode.W then
print("Stuff")
end
end)

The problem is that I want the function to fire while the key is pressed, and that I can just hold the key, and it'll keep printing "Stuff". Now, I have to press W every time I want to pring "Stuff"

Does anyone know how I would do something like this?

Thank you very much for your time!

1 answer

✓ Accepted answer

Issues

game is lowercase, not capitalized

Performing a Continuous Print

If you use the :GetKeysPressed() function of the UserInputService you can find all keys being held down by the user (these will be placed in a table).

Placing this into a loop will make it continue to run repeatedly, adding its function to the list once it's first pressed (don't forget the wait(#)!)

To check that the key "W" is pressed, we use an if-then statement

while true do
    for i, v in pairs(game:GetService("UserInputService"):GetKeysPressed()) do
	    if v.KeyCode == Enum.KeyCode.W then
		    print("Stuff")
	    end
    end
    wait()
end

2 comments

1

Whoops, that Game with a capital C was a little typo, anyways, thanks for the answer!

0

I meant capital G not C

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