The Input class
- Game Development course
- Beginner
- Lesson 43/83
- 4 min
Learn keyboard input with Input.GetKey and Input.GetKeyDown.
Keyboard Input and the Input Class
In Unity, the Input class is used for legacy input handling. The Input.GetKey method returns true during every frame while the player holds down the specified key. This method is preferred for continuous actions like running or firing while held.
if (Input.GetKey(KeyCode.W))
{
Debug.Log("Moving forward");
}Single Key Press: GetKeyDown
Input.GetKeyDown returns true only on the single frame when the player first presses the key, and will not trigger again until released and pressed again. It is ideal for instantaneous actions like jumping, opening menus, or single-shot firing. Similarly, Input.GetKeyUp triggers on the single frame the key is released.
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Jump triggered!");
}Practice Write Keyboard Control
Check the character's jump input. If Input.GetKeyDown(KeyCode.Space) is true, call Debug.Log("Ziplama");.
Starter code
using System;
public enum KeyCode { Space, Escape }
public static class Input
{
public static bool GetKeyDown(KeyCode key) => key == KeyCode.Space;
}
public static class Debug
{
public static void Log(object message) => Console.WriteLine(message);
}
public class Program
{
public static void Main()
{
// Space tusuna basildiginda Debug.Log ile "Ziplama" yazdir
}
}Sample solution
using System;
public enum KeyCode { Space, Escape }
public static class Input
{
public static bool GetKeyDown(KeyCode key) => key == KeyCode.Space;
}
public static class Debug
{
public static void Log(object message) => Console.WriteLine(message);
}
public class Program
{
public static void Main()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Ziplama");
}
}
}Expected output
Ziplama
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method is used to continuously check whether the player is holding down the W key every frame?
- Input.GetButton("Horizontal")
- Input.GetKeyDown(KeyCode.W)
- Input.GetKey(KeyCode.W) Correct answer
- Input.GetKeyUp(KeyCode.W)
Explanation: Input.GetKey returns true every frame the key is held down; GetKeyDown only returns true on the first frame it is pressed.
2 Catch the Jump Key
if (Input.____(KeyCode.Space))
if (Input.GetKeyDown(KeyCode.Space))
Explanation: For instantaneous actions like jumping, the GetKeyDown method is used to catch the first frame the key is pressed.
3 Key Methods Matching
| Term | Meaning |
|---|---|
Input.GetKey |
Returns true as long as key is held |
Input.GetKeyDown |
Returns true when key is first pressed |
Input.GetKeyUp |
Returns true when key is released |
KeyCode.Space |
Unity code for the spacebar key |