How to Handle Keyboard Input Using Unity

Without the ability to respond to user input, a video game becomes just a video. This is why Unity provides a robust input API that includes methods to check the status of the keyboard and mouse, retrieve input axis values from a joystick, read accelerometer data, and more. To get you started, this short tutorial focuses specifically on how to handle keyboard input using Unity.

Basic Keyboard Input Methods

You access Unity’s input system through static fields and methods of the aptly-named Input class. The following table summarizes the most important keyboard-related methods this class provides.

MethodPurpose
GetKey(string name)Determines if the named key is currently being held down.
GetKeyDown(string name)Returns true when the starts pressing the named key, regardless of how long it is held.
GetKeyUp(string name)Returns true when the user releases the named key.

Comparing GetKey and GetKeyDown

The GetKey and GetKeyDown functions serve similar purposes. However, they have important differences you should be aware of.

GetKey

  • Will continuously return true until the user releases the key.
  • Useful for automatically repeated actions, such as continuously firing a weapon. Also useful for toggleable modifiers, such as sprinting or crouching.
  • Can be called from Update, FixedUpdate, or any other time the key state is needed.

GetKeyDown

  • Will only return true during one frame. Key must be released and pressed again to reset.
  • Useful for triggering events that should happen exactly once per press, such as jumping or pausing the game.
  • Must be called from the Update function, since the true value only persists for a single frame.

Note that the GetKeyUp function behaves similarly to GetKeyDown, but is triggered when a key is released instead of pressed. With both methods, it is critical that they are only called in the Update function in order to ensure you do not miss any key presses.

Determining the Name of a Keyboard Key

All three of the basic input methods require the name of a key to check. Unity uses a set of naming conventions for keyboard keys. These conventions are detailed in the documentation, and summarized below:

Type of KeyNaming ConventionExamples
LettersLowercase lettera, b, c…
Number The number itself1, 2, 3…
NumpadNumber, symbol, or name (in brackets)[1], [2], [+], [equals], …
OthersLowercase key name. Spaces separate wordsescape, right shift, page up, …

For convenience, all three methods (GetKey, GetKeyDown, and GetKeyUp) are overloaded to accept a value from the KeyCode enum instead of a key name. You may prefer to use KeyCodes to gain benefits while coding such as autocomplete. Additionally, using a KeyCode will provide a compile-time guarantee that the argument is valid.

Code Example

I have added a sample Unity project to GitHub that demonstrates these functions. It has the following features:

  • Updates a message in real time as the spacebar key is pressed or released
  • Performs an action exactly one time when the escape key is pressed

I have included a screenshot of this (very exciting) demo to the right.

The spacebar handler use the GetKey function, as shown below:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SpacebarHandler : MonoBehaviour
{
    public Text spaceText;

    // note GetKey *can* be called from methods other than Update 
    void FixedUpdate()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            spaceText.text = "Space Pressed: TRUE";
        }
        else
        {
            spaceText.text = "Space Pressed: FALSE";
        }
    }
}

The handler for escape key presses uses the GetKeyDown method, which must only be called from inside Update:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EscapeHandler : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();

            // if run in the unity editor, this won't actually quit
            // so we log a message to show the keyboard handling works
            Debug.Log("Escape pressed!");
        }
    }
}

Conclusion

The methods described in this tutorial provide the easiest way to handle keyboard input in Unity. They are perfect for simple projects, such as Slash Racer. If your game has more advanced input requirements you should investigate alternatives. Such alternatives include Unity’s Input Manager or newer Input System. As your projects increase in complexity, products on the Asset store such as Rewired can help you take input processing to the next level. Future tutorials will cover these options in greater detail.

To read about these topics and more, browse my complete set of Unity tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *