Correct code to add a mouseover/mouse-hover/pointer-enter to #unity3d

This should be a 1-line feature, but Unity screwed it up. You can do it in approx. 12 lines of code, but I couldn’t find anywhere showing how, so I’ve written it up and you can copy/paste.

This is missing from the Unity docs (as of summer 2016).

This is missing from the Unity API’s and SDK (they implemented the code for “onClick” but failed to implement the code for the other GUI events – onHover / onEnter / onExit – etc).

The most-popular code on the internet is much too long and over-complicated, and requires creating new classes (that you don’t need) which pollute your code-base.

The less-popular but mostly correct code only works for Unity 4.6, and has some bugs that will prevent it working in most cases.

So I fixed it…

How it should work – but doesn’t

This is Unity’s code for adding a “click” handler to a button in their new (post-4.5) GUI:

Button b = ... // your button, from your code
b.onClick.AddListener( () => { YOUR_CODE_HERE } );

So the code for adding a “hover” handler (or, in 99% of SDK’s and platforms, an “enter/exit” pair of handlers) should be:

Button b = ... // your button, from your code
b.onEnter.AddListener( () => { YOUR_CODE_HERE } );
b.onExit.AddListener( () => { YOUR_CODE_HERE } );

Or, if they wanted to go with the 1% solution, that is only used by CSS:

b.onHover.AddListener( () => { YOUR_CODE_HERE } );

None of these work, because Unity’s API is incomplete.

Correct solution, Unity v5.0 – v5.4

Instead, you have to implement the missing code from Unity yourself. You can use this to do manual click detection, and to distinguish between mouse down and mouse up (a “click” is traditionally a pair of events: down followed by up. This is standard in all windowing systems and GUI API’s).

The most commonly needed case is hovering, so you’ll need two pieces of code, one for “mouse moves over” (enter) and one for “mouse moves away” (exit).

 * replace the code "YOUR_CODE_HERE_1" and "YOUR_CODE_HERE_2"
Button b = ... // your button, from your code

EventTrigger trigger = b.GetComponentInParent<EventTrigger>();
if( trigger == null ) trigger = b.gameObject.AddComponent<EventTrigger>();

EventTrigger.Entry entryEnter = new EventTrigger.Entry();
entryEnter.eventID = EventTriggerType.PointerEnter;
entryEnter.callback.AddListener( (eventData) => { YOUR_CODE_HERE_1(); } );

EventTrigger.Entry entryExit = new EventTrigger.Entry();
entryExit.eventID = EventTriggerType.PointerExit;
entryExit.callback.AddListener( (eventData) => { YOUR_CODE_HERE_2(); } );

One thought on “Correct code to add a mouseover/mouse-hover/pointer-enter to #unity3d

Leave a Reply

Your email address will not be published. Required fields are marked *