How to Use Input in Unity: Basic Guide and Examples
Input class to detect user actions like keyboard presses, mouse clicks, or touch gestures. Call methods like Input.GetKey, Input.GetMouseButtonDown, or Input.touchCount inside the Update() method to respond to input events.Syntax
The Input class provides several methods to check user input:
Input.GetKey(KeyCode key): Returns true while the specified key is held down.Input.GetKeyDown(KeyCode key): Returns true during the frame the user starts pressing the key.Input.GetMouseButtonDown(int button): Returns true during the frame the mouse button is pressed (0 for left button).Input.touchCount: Returns the number of touches currently on the screen (for mobile).
These methods are usually called inside the Update() method to check input every frame.
void Update() { if (Input.GetKeyDown(KeyCode.Space)) { Debug.Log("Space key was pressed this frame."); } if (Input.GetMouseButtonDown(0)) { Debug.Log("Left mouse button clicked."); } }
Example
This example shows how to move a game object left or right using arrow keys and detect mouse clicks to print messages in the console.
using UnityEngine; public class SimpleInputExample : MonoBehaviour { public float speed = 5f; void Update() { float move = 0f; if (Input.GetKey(KeyCode.LeftArrow)) { move = -speed * Time.deltaTime; } else if (Input.GetKey(KeyCode.RightArrow)) { move = speed * Time.deltaTime; } transform.Translate(move, 0, 0); if (Input.GetMouseButtonDown(0)) { Debug.Log("Mouse left button clicked!"); } } }
Common Pitfalls
Calling Input methods outside Update: Input checks should be inside Update() because input is checked every frame. Checking input in Start() or Awake() will not work as expected.
Using GetKeyDown vs GetKey: GetKeyDown triggers only once when the key is first pressed, while GetKey is true as long as the key is held. Use the right one for your need.
Not handling mobile input: Mouse input won't work on touch devices; use Input.touchCount and Input.GetTouch() for mobile.
void Update() { // Wrong: Checking input in Start will not detect key presses } void Start() { if (Input.GetKeyDown(KeyCode.Space)) { Debug.Log("Won't detect here"); } } // Correct way: void Update() { if (Input.GetKeyDown(KeyCode.Space)) { Debug.Log("Detected in Update"); } }
Quick Reference
Here is a quick summary of common Input methods:
| Method | Description | Use Case |
|---|---|---|
| Input.GetKey(KeyCode key) | True while key is held down | Continuous movement or action |
| Input.GetKeyDown(KeyCode key) | True only on the frame key is pressed | Single action trigger |
| Input.GetMouseButtonDown(int button) | True on mouse button press frame | Detect mouse clicks |
| Input.touchCount | Number of current touches | Detect touches on mobile |
| Input.GetTouch(int index) | Get touch details by index | Handle touch gestures |