How to Detect Key Press in Unity: Simple Guide
In Unity, you detect key presses using the
Input.GetKey or Input.GetKeyDown methods inside the Update() function. Input.GetKeyDown detects the moment a key is first pressed, while Input.GetKey detects if the key is held down.Syntax
Use Input.GetKey(KeyCode key) to check if a key is held down continuously. Use Input.GetKeyDown(KeyCode key) to detect the exact frame when the key is first pressed.
Both methods return a boolean: true if the key condition is met, otherwise false.
csharp
void Update() { if (Input.GetKeyDown(KeyCode.Space)) { // Code runs once when Space is pressed } if (Input.GetKey(KeyCode.Space)) { // Code runs every frame while Space is held } }
Example
This example prints messages to the Unity Console when the Space key is pressed or held.
csharp
using UnityEngine; public class KeyPressExample : MonoBehaviour { void Update() { if (Input.GetKeyDown(KeyCode.Space)) { Debug.Log("Space key was just pressed."); } if (Input.GetKey(KeyCode.Space)) { Debug.Log("Space key is being held down."); } } }
Output
Space key was just pressed.
Space key is being held down.
Space key is being held down.
... (repeats while held)
Common Pitfalls
- Using
Input.GetKeyDownoutsideUpdate()will not detect key presses properly because it only works per frame. - Confusing
Input.GetKeyDown(fires once) withInput.GetKey(fires continuously) can cause unexpected behavior. - Not using
KeyCodeenum values correctly, like passing strings instead ofKeyCode.
csharp
void Update() { // Wrong: Using GetKeyDown outside Update } // Correct usage: void Update() { if (Input.GetKeyDown(KeyCode.A)) { Debug.Log("A key pressed once."); } }
Quick Reference
| Method | Description | When to Use |
|---|---|---|
| Input.GetKey(KeyCode key) | Returns true while the key is held down | For continuous actions like moving a character |
| Input.GetKeyDown(KeyCode key) | Returns true only on the frame the key is first pressed | For single actions like jumping or shooting |
| Input.GetKeyUp(KeyCode key) | Returns true on the frame the key is released | For actions triggered on key release |
Key Takeaways
Use Input.GetKeyDown inside Update() to detect a key press once per frame.
Use Input.GetKey inside Update() to detect if a key is held down continuously.
Always use KeyCode enum values for keys, not strings.
Do not check key presses outside Update() or FixedUpdate() for reliable detection.
Understand the difference between GetKey, GetKeyDown, and GetKeyUp for correct behavior.