- Home /
OnMouseOver UI Button c#
How to detect in script, if the mouse is over a script-created button? If any component is needed, how can you create the object and set the component's settings in the right way?
Answer by Flaring-Afro · Jun 07, 2016 at 05:26 PM
You don't use OnMouseOver for UI elements, use IPointerEnterHandler Then attach script to game object that you want to implement it on.
example:
using UnityEngine.EventSystems;
public class MyClass: MonoBehaviour, IPointerEnterHandler{
public void OnPointerEnter(PointerEventData eventData)
{
//do stuff
}
Wrong! OnPointerEnter executes only once, while On$$anonymous$$ouseOver executes every frame.
Do you know why Unity choose to duplicate functionality like On$$anonymous$$ouseEnter
? And also why they didn't implement an equivalent IPointerXyzHandler
to On$$anonymous$$ouseOver
?
@JasonSpine I've implemented the analogous function: http://answers.unity.com/answers/1664400/view.html It's a shame they made this design choice. Would be interesting to know why.
Answer by AP124526435 · Sep 10, 2019 at 09:59 AM
I'm building on Flaring-Afro's answer. IPointerEnterHandler
works but is not the same as OnMouseOver
. To get this behaviour you (unfortunately) also need IPointerExitHandler
, a private bool and the Update
function such as:
public class UIElement : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
private bool mouse_over = false;
void Update()
{
if (mouse_over)
{
Debug.Log("Mouse Over");
}
}
public void OnPointerEnter(PointerEventData eventData)
{
mouse_over = true;
Debug.Log("Mouse enter");
}
public void OnPointerExit(PointerEventData eventData)
{
mouse_over = false;
Debug.Log("Mouse exit");
}
}
Your answer
Follow this Question
Related Questions
UI works in editor, but not on mobile device 1 Answer
I made an resume button, but I don't know how to code it to close my pause menu, any tips? 2 Answers
I need to move a sprite when an UI button is clicked 1 Answer
Change scene and play it by clicking UI Button? Scene does just load but not start playmode? 1 Answer