UserInputService & key input

Learn UserInputService and its importance.

by Goomiin

Author Avatar

Knowing UserInputService

First of all, you may ask: What is UserInputService? Well, UserInputService is directly related to the keyboard. Let's say you want to open an egg in a certain game, and the key you need to press to open the egg is the letter E. If you press E, the egg will open. That is just an example of how it works. It is actually very simple to make a script like this. Let's do it.

Creating the script

Create the script as a LocalScript, and place it in game.StarterPlayer.StarterPlayerScripts, or else it doesn't work. Now, you need to call it. You can use :GetService() for it.

local UserInputService = game:GetService("UserInputService")

Next, you will create a function using the event InputBegan. Notice how there are two values inside the function, and that is because both of them are necessary. However, we will only use one of them for this tutorial, which is input.

UserInputService.InputBegan:Connect(function(input, event)
    --Code goes here
end)

Now, you must create an if-statement for the key you want to be pressed, or else the whole function will trigger on every key that you press. Now, let's say you want to print that the player jumped everytime he pressed the spacebar. You would need to type the condition as input.KeyCode = Enum.KeyCode.Space, since we want it to print everytime we press the spacebar. Let's do it:

UserInputService.InputBegan:Connect(function(input, event)
    if input.KeyCode == Enum.KeyCode.Space then
        print("The player jumped!")
    end
end)

Explaining the script

Now, if the script did not have the if-statement, everytime you pressed a key, it would print "This player jumped!", even though he might have pressed any other key. The script would be like this:

UserInputService.InputBegan:Connect(function(input, event)
    print("The player jumped!")
end)

...and the output would be like this:

The player jumped! The player jumped! The player jumped! The player jumped! The player jumped! The player jumped!

...and you don't want it to print when he doesn't jump, so be sure to add the if-statement. If you have done everything correctly, the final script would be:

local UserInputService = game:GetService("UserInputService")

UserInputService.InputBegan:Connect(function(input, event)
    if input.KeyCode == Enum.KeyCode.Space then
        print("The player jumped!")
    end
end)

Final notes

There are some other events for UserInputService, like InputEnded, but it works the same way. InputBegan is the most important to learn as a beginner, since it's the one you are gonna use the most.

View in-game to comment, award, and more!