Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity global mouse events

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?

like image 644
zoosrc Avatar asked Sep 27 '14 13:09

zoosrc


2 Answers

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);
      ...
    }
  }

}
like image 93
Heisenbug Avatar answered Oct 13 '22 14:10

Heisenbug


Like stated, you can use it without major concerns, Unity will 'make its magic' internally as to set processing power sensitive code execution for you in terms of polling events. That's the beauty of a modern game engine after all. You normally shouldn't have to be hacking your way around a common feature such a mouse click detection.

However if you don't want to go using the main Update() you can make a CoRoutine if you feel more comfortable with that, just bear in mind that Unity coroutines are not multi-threaded neither, so at the end everything needs to wait anyway.

like image 23
CodeAssembler Avatar answered Oct 13 '22 14:10

CodeAssembler