0
0
Unityframework~5 mins

Keyboard input (GetKey, GetKeyDown) in Unity

Choose your learning style9 modes available
Introduction

We use keyboard input to let players control the game by pressing keys. GetKey checks if a key is held down, and GetKeyDown checks if a key was just pressed once.

Move a character continuously while a key is held down, like walking forward.
Trigger an action only once when a key is first pressed, like jumping.
Detect if a key is being held to charge a power or run faster.
Pause the game when the player presses the Escape key once.
Syntax
Unity
Input.GetKey(KeyCode.KeyName)
Input.GetKeyDown(KeyCode.KeyName)

GetKey returns true every frame the key is held down.

GetKeyDown returns true only on the first frame the key is pressed.

Examples
This moves the player forward as long as the W key is pressed.
Unity
if (Input.GetKey(KeyCode.W)) {
    // Move forward while W is held
}
This triggers a jump only once when the Space key is pressed.
Unity
if (Input.GetKeyDown(KeyCode.Space)) {
    // Jump once when Space is pressed
}
Holding Left Shift makes the player run faster.
Unity
if (Input.GetKey(KeyCode.LeftShift)) {
    // Run faster while holding Left Shift
}
Sample Program

This script prints "Moving forward" every frame while the W key is held down, and prints "Jump!" once when the Space key is pressed.

Unity
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            Debug.Log("Moving forward");
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("Jump!");
        }
    }
}
OutputSuccess
Important Notes

Use GetKeyDown for actions that should happen once per key press.

Use GetKey for continuous actions while the key is held.

Remember to check input inside the Update() method so it runs every frame.

Summary

GetKey detects if a key is held down continuously.

GetKeyDown detects the moment a key is first pressed.

Use these to control player actions smoothly and responsively.