Chapter 3. Input
Letting the player exert control over your game is, well, kind of important! It’s a core tenet of interactive games. In this chapter, we’ll look at some of the most common input requirements game developers have. Thankfully, Unity has a variety of input methods available, ranging from keyboard and mouse input to gamepad input to more sophisticated systems allowing for mouse pointer control. We’ll touch on each of them here.
Note
You’ll use both the legacy Input class, as well as Unity’s new input system in this chapter. They both have their place in a modern Unity project.
3.1 Getting Simple Keyboard Input
Problem
You want to know when the user is pressing keys on a keyboard, with as few steps as possible.
Solution
Use the legacy Input class’s GetKeyDown, GetKeyUp, and GetKey methods to find out what keys are being pressed:
if(Input.GetKeyDown(KeyCode.A)){Debug.Log("The A key was pressed!");}if(Input.GetKey(KeyCode.A)){Debug.Log("The A key is being held down!");}if(Input.GetKeyUp(KeyCode.A)){Debug.Log("The A key was released!");}if(Input.anyKeyDown){Debug.Log("A key was pressed!");}
Discussion
Each of these methods responds at different times:
-
GetKeyDownreturnstruewhen the key started being pressed on this frame. -
GetKeyUpreturnstruewhen the key was released on this frame. -
GetKeyreturnstrueif the key is currently being held down.
You can also use the anyKeyDown property to find out if any key at all is being pressed, which ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access