0
0
Unityframework~8 mins

Keyboard input (GetKey, GetKeyDown) in Unity - Performance & Optimization

Choose your learning style9 modes available
Performance: Keyboard input (GetKey, GetKeyDown)
MEDIUM IMPACT
This concept affects the responsiveness and smoothness of user input handling during gameplay.
Detecting a key press to trigger an action once per press
Unity
void Update() {
    if (Input.GetKeyDown(KeyCode.Space)) {
        // Action triggered only once when space is pressed
        Jump();
    }
}
GetKeyDown triggers the action only once per key press, reducing unnecessary repeated processing.
📈 Performance GainSingle input check per key press, improving responsiveness and lowering CPU load.
Detecting a key press to trigger an action once per press
Unity
void Update() {
    if (Input.GetKey(KeyCode.Space)) {
        // Action triggered every frame while space is held
        Jump();
    }
}
GetKey triggers the action every frame while the key is held, causing repeated processing and potential input flooding.
📉 Performance CostTriggers multiple input checks and repeated action calls per frame, increasing CPU usage and reducing input clarity.
Performance Comparison
PatternInput Checks per FrameRepeated ActionsCPU LoadVerdict
Using GetKey for single pressMultiple per frame while key heldYesHigh[X] Bad
Using GetKeyDown for single pressOne per key pressNoLow[OK] Good
Rendering Pipeline
Keyboard input checks occur during the game loop update phase before rendering. Efficient input handling reduces CPU load and prevents frame drops.
Input Processing
Game Logic Update
Rendering
⚠️ BottleneckInput Processing when using continuous checks like GetKey unnecessarily
Core Web Vital Affected
INP
This concept affects the responsiveness and smoothness of user input handling during gameplay.
Optimization Tips
1Use Input.GetKeyDown to detect a key press once per press.
2Avoid using Input.GetKey for actions that should trigger only once.
3Keep input handling code lightweight to maintain smooth frame rates.
Performance Quiz - 3 Questions
Test your performance knowledge
Which method is better for detecting a key press that should trigger an action only once per press?
AInput.GetKeyDown
BInput.GetKey
CInput.GetKeyUp
DInput.anyKey
DevTools: Profiler (Unity Profiler)
How to check: Open Unity Profiler, record while pressing keys, check CPU usage and number of calls in Input Processing and Update.
What to look for: Look for high CPU spikes or many repeated calls in Update when using GetKey versus fewer calls with GetKeyDown.