How to Get Keyboard Input (In Unity)
Nowadays, there are thousands of games available for users all around the world. Some of them are casual games, which are usually played for the sole purpose of spending time, some are serious games, which need players’ focus and concentration.
But for all of them, whether it’s a casual game or serious game, games need input. Games need players to give a command. It can be a touch (in android), a keyboard input, mouse input, or even joystick input. This time, we’re gonna see how to get a keyboard input, in a world of game programming, especially in Unity 5 Engine
Unity 5 provides various ways to get a keyboard input from user. There is GetKey.down / GetKey.up, there is GetAxis, there is GetButton and some other stuffs too. Today we will look forward of how to use GetKey.down in a very simple manner.
Okay first thing first, let’s open our Unity project. Therefore just create an empty game object. Look at this following screenshot
As we all already know, the input can be used for anything. Literally anything. We can use for example W A S D to move the characters as how it commonly works. We can use F button to fire (in a shooting game). We can use R game to reload (again, in shooting game). We can use space button to jump (as many games commonly do it). We can also set it differently, such as IJKL to move instead of WASD. But for the sake of player’s habit and comfort, developers tend to avoid it.
But this time, because it’s solely for demonstration purpose, we will simply create a log whenever an input is get from the engine. So let’s create a new script
if (Input.GetKeyDown (KeyCode.Space)) {
Debug.Log(“Space is pressed”);
}
Move that script to an empty game object and try it. As you can see on your console you can see “Space is pressed”
You can also add different conditions on your if conditionals.
For example you can print “Tab is pressed” or “Backspace is pressed” whenever that specific key is pressed. How to do that? Simply add it to your if conditionals
What will happen here is just as we expected it to happen before. Let’s play it
However, as I mentioned before, there are actually a lot of other options when it comes to getting a keyboard input.
And also, this can be used for various stuffs too. We can always be creative of how we manage the input from users
Author:
- Yogi Udjaja
- Houwen Lie