Unity – Checking for keyboard input

In this tutorial, you will be able to check for keyboard input from the user.

It’s a fairly simple process, and can be done in just a few keystrokes.

if(Input.GetKeyDown(KeyCode.KEY_YOU_WANT_TO_CHECK_FOR)){
    //Something happens
}

Replace KEY_YOU_WANT_TO_CHECK_FOR with whatever key you want, which you can find in Unity 3D’s documentation for the KeyCode.

One small pitfall is the enter key. The “enter” key on the keyboard is the return key, which is KeyCode.Return, not KeyCode.KeypadEnter. KeyCode.KeypadEnter will only work for the number pad’s enter key.

Also, the GetKeyDown method can accept either an enum or a String. KeyCode‘s fields are actually enums and not Strings, but it is accepted since GetKeyDown can accept different types of parameters.

It is generally better to use KeyCode instead of a String, since you are unlikely to make a mistake with KeyCode. For example, if you wanted to check for when the user presses the space bar, you can do it in one of two ways :

//First way with an enum :
if(Input.GetKeyDown(KeyCode.Space)){
    //Something happens
}

//Second way with a String :
if(Input.GetKeyDown("space")){
    //Something happens
}

Both are acceptable and will work fine. However, with the second method, there is nothing that stops someone from accidentally misspelling the word “space”. If you add an extra ‘e’ by accident, the compiler won’t warn you about it until run-time. However, if you try to write KeyCode.Spacee, the compiler will immediately complain that KeyCode.spacee doesn’t exist.

I hope this tutorial helped. Good luck!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s