0

I'm trying to make a toolbar system in my game but I can’t find a ways to detect a mouse click on a UI element only or to detect if it's over it, the regular detect system isn’t working.

I tried:

void OnMouseDown()
{
    Debug.Log(“yay”);
}

But the message is never logged.

Milan Egon Votrubec
  • 3,696
  • 2
  • 10
  • 24

2 Answers2

1

You can use EventSystems interfaces on your UI elements:

For example in your case:

public class test : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
{
    public void OnPointerClick(PointerEventData eventData)
    {
        Debug.Log("Click");
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("Enter");
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("Exit");
    }
}

Make sure your Scene has an EventSystem to make it works.

0

IsPointOverGameObject

The UI can be distinguished through the methods in the link above. You can use it like below.

private void Update()
{

    if (Input.GetMouseButtonDown(0))
    {
        if (EventSystem.current.IsPointerOverGameObject())
        {
            Debug.Log("Clicked UI");
        }
        else
        {
            Debug.Log("Clicked Not UI");
        }
    }
}
RedStone
  • 281
  • 2
  • 10
  • For cross-platform and cross-region compatibility (and probably deprecation in the future), I highly recommend to use [InputSystem](https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/index.html) instead of the old unity input. – LoïcLeGrosFrère Jan 31 '23 at 18:22