- Home /
The question is answered, right answer was accepted
[SOLVE] OnMouseEnter not working on UI elements
Hey guys!
First time asking here, I'm really new to scripting in C#, so this might be an over sight on my end, but I'm trying to change the alpha value of the image on the Button UI element.
So the results I'm trying to achieve is on start up, the Button is semi transparent, and when you mouse over the button, it will become fully opaque, and once the mouse leave, the button is transparent again.
This is the Script I made
private Button button;
public Color color;
void Start()
{
button = GetComponent<Button>();
color.a = .7f;
button.image.color = color;
print ("Start");
}
void OnMouseEnter()
{
color.a = 1f;
button.image.color = color;
print ("highlight");
}
void OnMouseExit()
{
color.a = 0.7f;
button.image.color = color;
print ("Exit");
}
I've tried adding both a Box Collider and a Box Collider2D but it still doesn't print anything on the console when I mouse over. Any help on the subject would be much appreciated!
Sincerely, Jason
Answer by meat5000 · Jul 02, 2015 at 03:54 PM
I do not think it works on UI elements.
It works on Colliders and "GUIElement" which is the name for the GUI system that was used before OnGUI.
The new UI uses Pointer methods which require you to 'implement' callbacks (IPointerEnterHandler etc) in your scripts and make use of the Event System.
http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseEnter.html
Thanks for replying! I've manage to succeed using Event Triggers.
I thought GUI and the new UI was the same thing, but guess they are not, thanks for clarifying that!
Answer by Chng · Jul 03, 2015 at 07:29 AM
Figured out! Add am Event Trigger component to the button. and add Poiner Enter Event Type. Drag the button that have the script and set the function!
But there's no method name's OnPointerOver to substitute On$$anonymous$$ouseOver if you want to call every frame while the mouse is over the GUIEliment or Collider,how can you figure out that?
you use OnPointerEnter in place of On$$anonymous$$ouseOver...
Note that you have to change "Runtime only" to "Editor and Runtime" if you want to test it out in the editor.
Other than that, worked perfectly, great advice! :)