Unity’s button / Input system has been the source of confusion for many newcomers. It’s no suprise, after all we have  GetKey, GetKeyDown, GetKeyUp,  GetButton, GetButtonDown, GetButtonUp.

So let’s try make sense of it all.

 

GetKey / GetKeyDown / GetKeyUp

Input.GetKey(…) will be familiar to developers coming from other platforms like Flash. It accepts either a KeyCode parameter OR a literal string representing that key.
If you hold down the key it will continue to fire, so it’s the equivalent of ‘this key is being held down’. So here comes the confuser… GetKeyDown in fact represents a single key stroke.
If you hold down a key with GetKeyDown it will only fire once, and to reset it the key must me released.

GetKey = machine gun

function Update () {
		if (Input.GetKey (KeyCode.Space))
			print ("space key is being held down");
	}
GetKeyDown =  single shot gun
function Update () {
		if (Input.GetKeyDown (KeyCode.Space))
			print ("space key was pressed once");
	}

finally we have the key released handler

function Update () {
		if (Input.GetKeyUp (KeyCode.Space))
			print ("space key was released");
	}
Here is a list of useful KeyCodes:
KeyCode.Mouse0   
KeyCode.Mouse1   
KeyCode.Space   
KeyCode.Tab      
KeyCode.UpArrow   
KeyCode.DownArrow
KeyCode.LeftArrow
KeyCode.RightArrow

The full list can be found here We can also type a string representing the button pressed, this can be good for fast coding but is generally not recommended as you have more chance of creating typo's.
function Update () {
 if (Input.GetKey ("space"))
 print ("space key is being held down");
 }

Here is a list of useful string for popular keys
“up”
“down”
“left”
“right”
“space”
“left shift”
“right shift”
“left ctrl”
“right ctrl”

 

GetButton / GetButtonDown/ GetButtonUp

The ‘get button’ functions work similarly to the ‘get key’ functions, except you cannot use KeyCodes, rather you are required to set your own buttons in the input manager. This is the recommended by Unity and can be quite powerful as it allows developers to map custom joystick / D-pad buttons.

By default Unity has already created some custom button inputs that can be accessed out of the box.

function Update () {
		if (Input.GetButtonDown ("Jump"))
			print ("space bar was pressed");
	}
function Update () {
		if (Input.GetButtonDown ("Fire1"))
			print ("left mouse button was pressed");
	}

To access the input manager go to Edit > Settings > Input.

InoutManager1

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The Input manager looks like this

The Input Manager

I wont go into specific details of how the Input manager works in this particular post as it is pretty self explanatory, I may however cover it in more detail in a separate post.
 InputManager unity documentation

 Video explaining the button system