Tip:
Highlight text to annotate it
X
In Unity GetKey or GetButton are ways
of receiving input from keys or joystick
buttons via Unity's input class.
The core differences between the two is
that GetKey specifically names keys for you
using key codes. For example, the Spacebar
is represented by KeyCode.Space
This works just fine for keyboard but it's
recommended that you use GetButton instead
and specify your own controls.
The input manager gives you the ability to
name an input and specify a key or button for it
and can be accessed by choosing
Edit - Project Settings - Input
from the top menu.
Then, when calling it, you can reference
a name using a string.
For example, Jump.
This is a default input represented by
the Spacebar, but we could put in a
different key or button code in order to
change the input that represents Jump.
Then when calling this button you can
reference the name using the string Jump.
To find out what to write in to your
positive button check the reference in the
documentation or look at the table
that accompanies this lesson.
When using GetKey or GetButton these inputs
have three states that return a Boolean.
True or false. First is GetKey or GetButton.
This will register true or false
depending on whether the button is being pressed
or not. So currently the key is not
being pressed so GetButton is returning false.
When we first press the key it then
returns true on the first frame,
then as we progress through frames,
holding down the button GetButtonDown
returns to false. GetButton still equals true
so we can check if the button is being held.
Then when we release the button GetButtonUp
shows true, but only again on the first frame.
As we continue, all values return to false.
So let's run through that again.
When the button is not being touched
everything is false.
When we first press the button we can
check for this using GetButtonDown,
which will return true. Also GetButton
will return true. After the first frame
GetButtonDown returns to false
so you can use this for tasks like
firing a weapon once. Then as we continue
to hold down only GetButton will return true.
Then when we release GetButtonUp
returns true for a single frame and then
thereafter returns back to false.
You should note that GetKey behaves
exactly the same way.
Only that the code is written slightly differently.
In order to check for a button
we use the string of the title that was placed
in the input manager, Jump.
But when checking for a very specific key
we can use KeyCodes.
Because this only pertains to the exact key
it's recommended that you use GetButton
and specify the inputs using the input manager
as shown earlier.