3
\$\begingroup\$

Been trying for days to figure out if there is a way to subscribe to keyboard/mouse events in unity. Instead of having to poll for them every frame and make my own events.

Right now I poll through the inputs and fire off my own events if a button is pressed. I'd prefer to subscribe directly to Unities input events, but have yet to figure out how.

I have a Unity Answers post that may have some relevant info to my question as well: http://answers.unity3d.com/questions/878485/is-there-a-more-efficient-way-to-make-events-for-k.html

\$\endgroup\$
6
\$\begingroup\$

There's no built-in way to do that. If you prefer an event based solution you can wrap all input polling inside a component and expose the relative and subscribe for them.

Some like:

public EventHandler : MonoBehaviour
{
  public event Action<Vector2> mouseCliked;

  void Update()
  {
    if (Input.GetMouseButtonDown(0))
    {
      mouseCliked(mousePosition);
    }
    ....
  }
}
\$\endgroup\$
  • \$\begingroup\$ Thanks Heisenbug,bit sad that I can't But I can deal with it. \$\endgroup\$ – Douglas Gaskell Jan 24 '15 at 17:02
2
\$\begingroup\$

As said by Heisenbug is no built-in way to do this.

My recommendation is to explore the UnityEvent namespace new to Unity 4.6 and above. This will allow you to expose functionality to designers that will allow them to rig up interesting inputs and receivers.

You can go the extra mile and implement a custom editor with a serialized dictionary and button to add new listeners.

Edit: If you need to describe you could go with the dreaded singleton and process subscription requests to provide KeyCodes and press types.

\$\endgroup\$
  • 1
    \$\begingroup\$ @that's true...UnityEvent could be a nice way to serialize delegates. \$\endgroup\$ – Heisenbug Jan 23 '15 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.