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:
-
GetKeyDown
returnstrue
when the key started being pressed on this frame. -
GetKeyUp
returnstrue
when the key was released on this frame. -
GetKey
returnstrue
if 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 ...
Get Unity Development Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.