- Home /
How can I detect which key or mouse button was pressed?
I'm working on a keybindings menu and struggling with detecting whether the player presses a key or a mouse button. Currently my code looks like this:
Event keyEvent;
keyEvent = new Event();
keyEvent = Event.current;
if (recordingAttack)
{
if (keyEvent.isKey)
{
Settings.Attack = keyEvent.keyCode;
}
if (keyEvent.isMouse)
{
if (keyEvent.button == 0)
Settings.Attack = KeyCode.Mouse0;
else if (keyEvent.button == 1)
Settings.Attack = KeyCode.Mouse1;
else if (keyEvent.button == 2)
Settings.Attack = KeyCode.Mouse2;
else if (keyEvent.button == 3)
Settings.Attack = KeyCode.Mouse3;
else if (keyEvent.button == 4)
Settings.Attack = KeyCode.Mouse4;
else if (keyEvent.button == 5)
Settings.Attack = KeyCode.Mouse5;
else if (keyEvent.button == 6)
Settings.Attack = KeyCode.Mouse6;
}
recordingAttack = false;
Attack.text = Settings.Attack.ToString();
}
This code is running in update and there is one of these if statements for each keybinding, I know it is not a very efficient way but I'm rather new to code and wanted to try it myself. Any help is much appreciated :)
Input.GetKeyDown(KeyCode.$$anonymous$$ouse0);
Input.GetKey(KeyCode.$$anonymous$$ouse0);
Input.GetKeyUp(KeyCode.$$anonymous$$ouse0);
Is it what you're looking for?
I don't believe so, I'm trying to figure out why my code for if (keyEvent.isKey) isn't working. In the editor it gives the following error: "NullReferenceException: Object reference not set to an instance of an object" I've found it sends this error on the if statement I specified above and I'm not sure why...
Answer by tuinal · Jul 24, 2020 at 10:55 PM
if (Input.GetKeyDown(KeyCode.W) // returns true on only the single frame the W key was pressed
if (Input.GetKey(KeyCode.W) // returns true every frame W is pressed
if(Input.GetKeyUp(KeyCode.W) // returns true only on the frame W was released
if(Input.GetButtonDown("Fire1") /returns true on the single frame whatever is bound to "Fire1" in edit>project settings>input.
if(Input.GetAxis("Horizontal") returns a float in the range -1 to 1 based on the axis defined as "Horizontal" in edit>project settings>input.
Obviously KeyCode.W can be changed for any key. Input.GetMouseButtonDown(0) is also LMB, (1) is RMB. It's generally better to use GetButtonDown or GetAxis since they can be rebound easily or mapped to multiple devices, whereas GetKey is hardcoded to that key.
Your answer
