Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Question: How do I detect if the mouse is over any UI element? [UI Elements]

Discussion in 'UI Toolkit' started by erlapso, Feb 16, 2020.

  1. erlapso

    erlapso

    Joined:
    Apr 7, 2019
    Posts:
    6
    In the old Unity UI I would have
    `EventSystem.current.IsPointerOverGameObject()`
    and that would work in stuff like (pseudo code follows)
    `getbuttondown("fire1") if ( EventSystem.current.IsPointerOverGameObject() ) } do nothing { else } `
    Now im trying to switch to UIElements - which looks awesome - but I really need to be able to tell if the user is clicking on the UI or somewhere else. How do I do that? I could not find it in the docs
     
  2. VOTRUBEC

    VOTRUBEC

    Joined:
    Dec 17, 2014
    Posts:
    70
    Do you want to know when the mouse enters and leaves the VisualElement, or when the MouseUpEvent/MouseDownEvents occur?

    Depending on your need, one of these should do the trick:

    Code (CSharp):
    1. yourElement.RegisterCallback<MouseEnterEvent> ( x => OnMouseEnter ( x ) );
    2. yourElement.RegisterCallback<MouseLeaveEvent> ( x => OnMouseLeave ( x ) );
    3. yourElement.RegisterCallback<MouseUpEvent> ( x => OnMouseUp ( x ) );
     
    jGate99 likes this.
  3. PMacDev

    PMacDev

    Joined:
    Sep 8, 2020
    Posts:
    7
    This would work for a one-off, but what if you would want to do this for ALL of the elements, so essentially checking if the player is clicking a UI Element or trying to interact with the game?
     
  4. Arkenhammer

    Arkenhammer

    Joined:
    Nov 10, 2019
    Posts:
    11
    What I did was create my own custom background element for each UI panel which goes over my game; those panels register/unregister themselves in a list of UI areas (via an interface). Then when my game gets a mouse click it runs through each of the areas to see if the mouse is in a UI area and, if so, it rejects the click and lets the UI Event system handle it. It's not pretty, particularly for panels which move or animate but, for my game, it got me the enough to replace the old "IsMouseOverUI" functionality.

    Note: MouseEnterEvent and MouseLeaveEvent do not solve this problem because the mouse will "Leave" the background when it enters an interactable child element. Adding mouse enter/leave to 100s of elements in the UI is not really an option so rectangle testing it is.
     
unityunity