Unity global mouse events

zoosrc picture zoosrc · Sep 27, 2014 · Viewed 7.7k times · Source

Most Unity tutorials suggest using Mouse events within the Update function, like this:

function Update () {

   if (UnityEngine.Input.GetMouseButton(1)) { 

   } 

}

This strikes me as really inefficient though, similar to using onEnterFrame in AS or setInterval in JS to power the whole application - I'd really prefer to use an events based system.

the OnMouseDown() method is useful, but is only fired when the MouseDown is on the object, not anywhere in the scene.

So here's the question: Is there a MouseEvent in Unity for detecting if the mouse button is down globally, or is the Update solution the recommended option?

Answer

Heisenbug picture Heisenbug · Sep 27, 2014

This strikes me as really inefficient though, similar to using onEnterFrame in AS or setInterval in JS to power the whole application - I'd really prefer to use an events based system.

As already pointed out in comments, this isn't necessary less efficient. Every event based system is probably using a polling routine like that behind the scenes, updated at a given frequency.

In many game engines/frameworks you are going to find a polling based approach for input handling. I think this is related to the fact that input update frequency is directly correlated to the frame rate/update loop frequency. In fact it doesn't make much sense to listen for input at higher or lower frequency than your game loop.

So here's the question: Is there a MouseEvent in Unity for detecting if the mouse button is down globally, or is the Update solution the recommended option?

No there isn't. Btw if you want you can wrap mouse input detection inside a single class, and expose events from there where other classes can register to. Something like:

public class MouseInputHandler : MonoBehavior
{
  public event Action<Vector2> MousePressed;
  public event Action<Vector2> MouseMoved;
  ...

  void Update()
  {
    if (Input.GetMouseButton(0))
    {
      MousePressed(Input.mousePosition);
      ...
    }
  }

}