Search Unity

EventSystem - Get current GO under pointer?

Discussion in 'UGUI & TextMesh Pro' started by Democide, Jan 10, 2019.

  1. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    315
    Hey y'all,

    I'm looking for a quick way (cause it's in Update) to get the object currently under the pointer. Looking at the PointerInputModule and the PointerEventData there's pointerEventData.pointerEnter which is the GO but I don't have access to that in update, and EventSystem only gives me access to IsPointerOverGameObject().

    I'm asking because I want to check if the object is actually interactable and then create different behaviors based on that.
     
  2. bentontr

    bentontr

    Joined:
    Jun 9, 2017
    Posts:
    39
    You can inherit the standalone input module and retrieve the cached data from the event system.

    Code (CSharp):
    1. public class CustomStandaloneInputModule : StandaloneInputModule
    2. {
    3.     public GameObject GetHovered()
    4.     {
    5.         var mouseEvent = GetLastPointerEventData(-1);
    6.         if (mouseEvent == null)
    7.             return null;
    8.         return mouseEvent.pointerCurrentRaycast.gameObject;
    9.     }
    10.  
    11.     public List<GameObject> GetAllHovered()
    12.     {
    13.         var mouseEvent = GetLastPointerEventData(-1);
    14.         if (mouseEvent == null)
    15.             return null;
    16.         return mouseEvent.hovered;
    17.     }
    18. }
     
  3. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    315
    Mhm. I was afraid something like this was needed. It's a bit weird that this is not readily available tho
     
  4. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @Democide

    Or you could raycast using GraphicRaycaster, only when you are over some object?

    Code (CSharp):
    1.    
    2. List<RaycastResult> RaycastUI()
    3. {
    4.     List<RaycastResult> results = new List<RaycastResult>();
    5.     gr.Raycast(new PointerEventData(EventSystem.current) { position = Input.mousePosition }, results);
    6.     return results;
    7. }
    8.  
     
    Democide likes this.