Input must must read from the Update function.
Reference for all the available Keycode enum.
1. Reading key press with Input.GetKey
:
Input.GetKey
will repeatedly return true
while the user holds down the specified key. This can be used to repeatedly fire a weapon while holding the specified key down. Below is an example of bullet auto-fire when the Space key is held down. The player doesn't have to press and release the key over and over again.
public GameObject bulletPrefab;
public float shootForce = 50f;
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
Debug.Log("Shooting a bullet while SpaceBar is held down");
//Instantiate bullet
GameObject bullet = Instantiate(bulletPrefab, transform.position, transform.rotation) as GameObject;
//Get the Rigidbody from the bullet then add a force to the bullet
bullet.GetComponent<Rigidbody>().AddForce(bullet.transform.forward * shootForce);
}
}
2.Reading key press with Input.GetKeyDown
:
Input.GetKeyDown
will true only once when the specified key is pressed. This is the key difference between Input.GetKey
and Input.GetKeyDown
. One example use of its use is to toggle a UI or flashlight or an item on/off.
public Light flashLight;
bool enableFlashLight = false;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//Toggle Light
enableFlashLight = !enableFlashLight;
if (enableFlashLight)
{
flashLight.enabled = true;
Debug.Log("Light Enabled!");
}
else
{
flashLight.enabled = false;
Debug.Log("Light Disabled!");
}
}
}
3.Reading key press with Input.GetKeyUp
:
This is the exact opposite of Input.GetKeyDown
. It is used to detect when key-press is released/lifted. Just like Input.GetKeyDown
, it returns true
only once. For example, you can enable
light when key is held down with Input.GetKeyDown
then disable the light when key is released with Input.GetKeyUp
.
public Light flashLight;
void Update()
{
//Disable Light when Space Key is pressed
if (Input.GetKeyDown(KeyCode.Space))
{
flashLight.enabled = true;
Debug.Log("Light Enabled!");
}
//Disable Light when Space Key is released
if (Input.GetKeyUp(KeyCode.Space))
{
flashLight.enabled = false;
Debug.Log("Light Disabled!");
}
}