Keyborad Input Functions in Unity
Notes:
Unity Scripting API - Keyboard Input Functions :
- in Unity we have variety of static properties & methods as part of the Input class
- they are used to detect different status of a given key on the keyboard
public static bool GetKeyDown (KeyCode key / String key);
- returns true as soon as a given key on the keyboard is pressed
public static bool GetKey (KeyCode key / String key);
- returns true as long as a given key on the keyboard is held down
public static bool GetKeyUp (KeyCode key / String key);
- returns true as soon as a given key on the keyboard is released
Note: while using these methods, you must use first GetKeyDown, NextGetKey and then GetKeyUp i.e. they must be used in an order
Example code:
if (Input.GetKeyDown (KeyCode.Space)) {
Debug.Log ("Space key is pressed");
}
if (Input.GetKey (KeyCode.Space)) {
Debug.Log ("Space key is held down");
}
if (Input.GetKeyUp (KeyCode.Space)) {
Debug.Log ("Space key is released");
}
// OR
if (Input.GetKeyDown ("space")) {
Debug.Log ("Space key is pressed");
}
if (Input.GetKey ("space")) {
Debug.Log ("Space key is held down");
}
if (Input.GetKeyUp ("space")) {
Debug.Log ("Space key is released");
}