0
0
UnityHow-ToBeginner ยท 3 min read

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.GetKeyDown outside Update() will not detect key presses properly because it only works per frame.
  • Confusing Input.GetKeyDown (fires once) with Input.GetKey (fires continuously) can cause unexpected behavior.
  • Not using KeyCode enum values correctly, like passing strings instead of KeyCode.
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

MethodDescriptionWhen to Use
Input.GetKey(KeyCode key)Returns true while the key is held downFor continuous actions like moving a character
Input.GetKeyDown(KeyCode key)Returns true only on the frame the key is first pressedFor single actions like jumping or shooting
Input.GetKeyUp(KeyCode key)Returns true on the frame the key is releasedFor 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.