Performance: Keyboard input (GetKey, GetKeyDown)
This concept affects the responsiveness and smoothness of user input handling during gameplay.
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
// Action triggered only once when space is pressed
Jump();
}
}void Update() {
if (Input.GetKey(KeyCode.Space)) {
// Action triggered every frame while space is held
Jump();
}
}| Pattern | Input Checks per Frame | Repeated Actions | CPU Load | Verdict |
|---|---|---|---|---|
| Using GetKey for single press | Multiple per frame while key held | Yes | High | [X] Bad |
| Using GetKeyDown for single press | One per key press | No | Low | [OK] Good |
Input.GetKeyDown(KeyCode.Space) detect in Unity?Input.GetKeyDown returns true only on the first frame the key is pressed.KeyCode.Space is used, it detects the first press of the space bar only.Input.GetKey returns true every frame the key is held down.Input.GetKey(KeyCode.W) to check if "W" is held.void Update() {
if (Input.GetKeyDown(KeyCode.A)) {
Debug.Log("Pressed A");
}
if (Input.GetKey(KeyCode.A)) {
Debug.Log("Holding A");
}
}Input.GetKeyDown(KeyCode.A) triggers only once when the key is first pressed.Input.GetKey(KeyCode.A) triggers every frame while the key is held down, so it prints repeatedly during 3 seconds.void Update() {
if (Input.GetKeyDown("space")) {
Debug.Log("Jump!");
}
}Input.GetKeyDown requires a KeyCode parameter, not a string like "space".Input.GetKeyDown(KeyCode.Space).void Update() {
// Your code here
}Input.GetKeyDown(KeyCode.Space).Input.GetKey(KeyCode.LeftArrow).Pass the test and this pattern moves unknown