0
0
Unityframework~15 mins

Keyboard input (GetKey, GetKeyDown) in Unity - Deep Dive

Choose your learning style9 modes available
Overview - Keyboard input (GetKey, GetKeyDown)
What is it?
Keyboard input in Unity lets your game detect when a player presses keys on their keyboard. GetKey and GetKeyDown are two ways to check if a key is being pressed or was just pressed this frame. GetKey returns true as long as the key is held down, while GetKeyDown returns true only on the exact frame the key was first pressed. This helps games respond to player actions smoothly and accurately.
Why it matters
Without keyboard input detection, games would not know what the player wants to do, like moving a character or jumping. GetKey and GetKeyDown solve the problem of knowing exactly when and how long a key is pressed, which is crucial for responsive controls. Without these, games would feel unresponsive or behave unpredictably, frustrating players.
Where it fits
Before learning keyboard input, you should understand basic Unity scripting and the Update method where input checks happen. After mastering GetKey and GetKeyDown, you can learn about more advanced input systems like GetKeyUp, Input Actions, or handling multiple input devices.
Mental Model
Core Idea
GetKey checks if a key is held down continuously, while GetKeyDown detects the exact moment a key is first pressed.
Think of it like...
Imagine a light switch: GetKey is like holding the switch down to keep the light on, and GetKeyDown is like flipping the switch on just once to start the light.
┌───────────────┐
│ Frame 1       │
│ Key pressed   │
│ GetKeyDown: ✔ │
│ GetKey: ✔     │
└───────────────┘
      ↓
┌───────────────┐
│ Frame 2       │
│ Key held      │
│ GetKeyDown: ✘ │
│ GetKey: ✔     │
└───────────────┘
      ↓
┌───────────────┐
│ Frame 3       │
│ Key released  │
│ GetKeyDown: ✘ │
│ GetKey: ✘     │
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Unity Input Basics
🤔
Concept: Learn how Unity detects keyboard input using the Input class inside the Update method.
In Unity, the Input class lets you check keyboard keys. You usually check keys inside the Update() method because it runs every frame. For example, Input.GetKey(KeyCode.Space) returns true if the spacebar is held down during that frame.
Result
You can detect if a key is currently pressed every frame.
Knowing that input checks happen every frame inside Update is key to making responsive controls.
2
FoundationDifference Between GetKey and GetKeyDown
🤔
Concept: Understand the difference between continuous key press detection and single press detection.
GetKey returns true every frame the key is held down. GetKeyDown returns true only on the first frame the key is pressed. For example, holding spacebar makes GetKey true every frame, but GetKeyDown true only once when you first press it.
Result
You can choose whether to react once or continuously to a key press.
This difference lets you control if an action happens once or repeatedly while holding a key.
3
IntermediateUsing GetKey for Continuous Actions
🤔Before reading on: Do you think GetKey triggers an action once or repeatedly while holding a key? Commit to your answer.
Concept: Learn how to use GetKey to perform actions continuously while a key is held.
Example: Move a character forward while the W key is held. void Update() { if (Input.GetKey(KeyCode.W)) { transform.Translate(Vector3.forward * speed * Time.deltaTime); } } This moves the character every frame the W key is pressed.
Result
The character moves smoothly forward as long as the key is held.
Using GetKey for continuous input matches how players expect holding a key to cause ongoing movement.
4
IntermediateUsing GetKeyDown for Single Actions
🤔Before reading on: Will GetKeyDown trigger multiple times if you hold the key? Commit to yes or no.
Concept: Use GetKeyDown to trigger actions that should happen only once per key press.
Example: Make the character jump only once when spacebar is pressed. void Update() { if (Input.GetKeyDown(KeyCode.Space)) { Jump(); } } Jump() runs only once per press, even if spacebar is held.
Result
The character jumps once per key press, not repeatedly.
GetKeyDown prevents repeated triggering of actions that should happen once, like jumping.
5
IntermediateCombining GetKey and GetKeyDown
🤔
Concept: Learn to combine both methods to handle complex input scenarios.
Example: Hold Shift to run faster, but jump only once per press. void Update() { if (Input.GetKey(KeyCode.LeftShift)) { speed = runSpeed; } else { speed = walkSpeed; } if (Input.GetKeyDown(KeyCode.Space)) { Jump(); } } This lets you run continuously and jump once per press.
Result
Player runs faster while holding Shift and jumps once per spacebar press.
Combining both input checks lets you build natural and responsive controls.
6
AdvancedHandling Input Frame Timing
🤔Before reading on: Do you think GetKeyDown can miss a key press if the frame rate is low? Commit to yes or no.
Concept: Understand how frame rate affects input detection and how to avoid missed inputs.
GetKeyDown returns true only on the frame the key is pressed. If the game runs at low frame rate, a quick tap might be missed because the key press happens between frames. To avoid this, keep frame rates high or use input buffering techniques.
Result
You learn why some quick key presses might not register and how to prevent it.
Knowing input depends on frame timing helps you design controls that feel reliable even on slow devices.
7
ExpertInternals of Unity Input System
🤔Before reading on: Do you think Unity polls hardware every frame or uses event-driven input? Commit to your answer.
Concept: Explore how Unity's Input class polls keyboard state each frame from the operating system.
Unity's Input system queries the OS keyboard state every frame during Update. GetKey and GetKeyDown check this state snapshot. GetKeyDown compares current and previous frame states to detect new presses. This polling approach is simple but requires careful timing to avoid missed inputs.
Result
You understand why input checks must be in Update and why timing matters.
Understanding Unity polls input every frame explains why input detection depends on frame rate and Update timing.
Under the Hood
Unity's Input system queries the operating system's keyboard state once per frame during the Update phase. GetKey checks if the key is currently down in this snapshot. GetKeyDown compares the current frame's key state with the previous frame's to detect the transition from up to down. This means GetKeyDown is true only on the exact frame the key changes state.
Why designed this way?
Polling input every frame is simple and consistent across platforms. It fits Unity's frame-based game loop model. Event-driven input would be more complex to integrate with frame updates and could cause timing issues. The design balances simplicity, performance, and cross-platform compatibility.
┌───────────────┐
│ OS Keyboard   │
│ State         │
└──────┬────────┘
       │ Polled every frame
┌──────▼────────┐
│ Unity Input   │
│ System       │
│ - Current frame state
│ - Previous frame state
└──────┬────────┘
       │
       │ GetKey: checks current state
       │ GetKeyDown: compares current vs previous
       ▼
┌───────────────┐
│ Game Script   │
│ Input Checks  │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does GetKeyDown return true every frame while holding a key? Commit to yes or no.
Common Belief:GetKeyDown returns true every frame as long as the key is held down.
Tap to reveal reality
Reality:GetKeyDown returns true only on the first frame the key is pressed, not continuously.
Why it matters:Misusing GetKeyDown for continuous actions causes controls to feel unresponsive or actions to trigger only once.
Quick: Can GetKeyDown miss a key press if the frame rate is very low? Commit to yes or no.
Common Belief:GetKeyDown always detects every key press regardless of frame rate.
Tap to reveal reality
Reality:GetKeyDown can miss very quick key presses if they happen between frames at low frame rates.
Why it matters:Players might feel controls are unresponsive or buggy on slow devices if input is missed.
Quick: Is it okay to check GetKey or GetKeyDown outside Update? Commit to yes or no.
Common Belief:You can check GetKey or GetKeyDown anytime in your code and get accurate results.
Tap to reveal reality
Reality:Input checks should happen inside Update or similar frame methods because input state updates once per frame.
Why it matters:Checking input outside Update can cause stale or incorrect input detection, leading to bugs.
Quick: Does GetKeyDown detect key releases? Commit to yes or no.
Common Belief:GetKeyDown detects when a key is released.
Tap to reveal reality
Reality:GetKeyDown detects only the moment a key is pressed down; key releases are detected by GetKeyUp.
Why it matters:Confusing these causes wrong input handling, like triggering actions on release instead of press.
Expert Zone
1
GetKeyDown only triggers once per press even if multiple scripts check it in the same frame, preventing duplicate actions.
2
Input polling timing means input state is fixed during Update; reading input in FixedUpdate can cause missed or delayed detection.
3
Using GetKey with Time.deltaTime ensures smooth movement independent of frame rate, avoiding jerky controls.
When NOT to use
Avoid GetKey and GetKeyDown for complex input needs like rebinding keys, multiple devices, or gestures. Use Unity's newer Input System package instead, which supports event-driven input, action maps, and better device support.
Production Patterns
In real games, GetKey is used for continuous movement or aiming, GetKeyDown for single actions like jumping or shooting. Developers combine them with input buffering and cooldown timers to handle fast or overlapping inputs reliably.
Connections
Event-driven Input Systems
GetKey/GetKeyDown are polling-based, while event-driven systems react to input events asynchronously.
Understanding polling input clarifies why event-driven input can reduce missed inputs and improve responsiveness in complex applications.
Game Loop Architecture
Input polling fits into the game loop's Update phase, syncing input checks with game state updates.
Knowing how input fits in the game loop helps design smooth, frame-consistent gameplay experiences.
Human Reaction Time in Psychology
Keyboard input timing relates to how fast humans can press keys and expect feedback.
Understanding human reaction times guides how sensitive input detection should be to feel natural and responsive.
Common Pitfalls
#1Using GetKeyDown to move a character continuously.
Wrong approach:void Update() { if (Input.GetKeyDown(KeyCode.W)) { transform.Translate(Vector3.forward * speed * Time.deltaTime); } }
Correct approach:void Update() { if (Input.GetKey(KeyCode.W)) { transform.Translate(Vector3.forward * speed * Time.deltaTime); } }
Root cause:Confusing GetKeyDown (single press) with GetKey (continuous press) causes movement to happen only once instead of smoothly.
#2Checking input outside Update causing stale input state.
Wrong approach:void Start() { if (Input.GetKeyDown(KeyCode.Space)) { Jump(); } }
Correct approach:void Update() { if (Input.GetKeyDown(KeyCode.Space)) { Jump(); } }
Root cause:Input state updates once per frame during Update; checking input in Start or other methods misses current frame input.
#3Ignoring frame rate effects and missing quick key presses.
Wrong approach:void Update() { if (Input.GetKeyDown(KeyCode.Space)) { Jump(); } } // No frame rate consideration or input buffering
Correct approach:// Implement input buffering or ensure high frame rate to catch quick presses void Update() { if (Input.GetKeyDown(KeyCode.Space)) { Jump(); } }
Root cause:Not accounting for frame timing causes missed inputs on slow devices or quick taps.
Key Takeaways
GetKey returns true every frame a key is held down, enabling continuous actions like movement.
GetKeyDown returns true only on the first frame a key is pressed, perfect for single-trigger actions like jumping.
Input checks must happen inside Update to get accurate, current keyboard states each frame.
Frame rate affects input detection; low frame rates can cause missed key presses with GetKeyDown.
Understanding Unity's input polling model helps design responsive and reliable player controls.