C# Unity Event -- Reading Additional Mouse Buttons

Viewed 563

I am determining KeyCode inputs by Event.current.keyCode or Event.current.button.

When Event.current.isMouse == true, Event.current.button will only return 0,1, or 2 (left, right, or middle click).

It never recognizes a Mouse3 or 4 button.

Does anyone have any info on this?

3 Answers

This might be a bug or limitation of the Event class. You can get access to these buttons using Unity's Input class. It is a bit misleading through since you do this trough GetKeyDown rather than GetMouseButtonDown.

public class ButtonTest : MonoBehaviour
{
    private void Update()
    {
        if (UnityEngine.Input.GetKeyDown(KeyCode.Mouse0))
        {
            Debug.Log("Mouse 0");
        }
        if (UnityEngine.Input.GetKeyDown(KeyCode.Mouse1))
        {
            Debug.Log("Mouse 1");
        }
        if (UnityEngine.Input.GetKeyDown(KeyCode.Mouse2))
        {
            Debug.Log("Mouse 2");
        }
        if (UnityEngine.Input.GetKeyDown(KeyCode.Mouse3))
        {
            Debug.Log("Mouse 3");
        }
        if (UnityEngine.Input.GetKeyDown(KeyCode.Mouse4))
        {
            Debug.Log("Mouse 4");
        }
        if (UnityEngine.Input.GetKeyDown(KeyCode.Mouse5))
        {
            Debug.Log("Mouse 5");
        }
        if (UnityEngine.Input.GetKeyDown(KeyCode.Mouse6))
        {
            Debug.Log("Mouse 6");
        }
    }
}

I ran into the same problem. The example code given on the Unity Scripting API implies that the other mouse buttons are accessible through Event.button however I have not been able to find a way to access them.

using UnityEngine;

public class Example : MonoBehaviour
{
    // Detect which mouse button is currently pressed
    // and print it.
    void OnGUI()
    {
        Event e = Event.current;
        if (e.button == 0 && e.isMouse)
        {
            Debug.Log("Left Click");
        }
        else if (e.button == 1)
        {
            Debug.Log("Right Click");
        }
        else if (e.button == 2)
        {
            Debug.Log("Middle Click");
        }
        else if (e.button > 2)
        {
            Debug.Log("Another button in the mouse clicked");
        }
    }
}

If you are checking for every possible mouse keys for key config purposes, than you can do something like this, because the mouse key codes are next to each other:

private void OnGUI()
{
 
  KeyCode key;
  for (int i = (int)KeyCode.Mouse0; i <= (int)KeyCode.Mouse6; i++)
  {
    if (Input.GetKey((KeyCode)i))
    {
       key = (KeyCode)i;
       break;
    }
  } 
  //do something with the key here
 
}

So in this way you don't have to write out 7 if statements, and will break out of the cycle if it finds the key code.

Related