Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Bug IsPointerOverGameObject(0) always returns false

Discussion in 'UGUI & TextMesh Pro' started by tomsseisums, Aug 13, 2023.

  1. tomsseisums

    tomsseisums

    Joined:
    Oct 8, 2012
    Posts:
    37
    I have a hard time figuring out why would IsPointerOverGameObject(0) always return false, even when RaycastAll returns something.

    Here code:
    Code (CSharp):
    1. void IsPointerOverGameObject(int pointerId) {
    2.     return EventSystem.current.IsPointerOverGameObject(pointerId);
    3. }
    4.  
    5. GameObject GetTopMostObjectUnderPointer(int pointerId, Vector2 position)
    6. {
    7.     var raycastResults = new List<RaycastResult>();
    8.  
    9.     EventSystem.current.RaycastAll(new PointerEventData(EventSystem.current)
    10.     {
    11.         pointerId = pointerId,
    12.         position =  position
    13.     }, raycastResults);
    14.    
    15.     return raycastResults.Count > 0 ? raycastResults[0].gameObject : null;
    16. }
    17.  
    18. void Update()
    19. {
    20.     if (Input.GetMouseButtonDown(0))
    21.     {
    22.         Debug.Log($"[IsPointerOverGameObject = {IsPointerOverGameObject(0)}] [TopMostGameObject = {GetTopMostObjectUnderPointer(0, Input.mousePosition)}] [Selected Object = {EventSystem.current.currentSelectedGameObject}]");
    23.     }
    24. }
    25.  
    Here screenshot:
    upload_2023-8-13_2-45-55.png
    #1 I have clicked the button
    #2 All the raycasting settings are setup as they should be, otherwise UI doesn't handle anything
    #3 IsPointerOverGameObject(0) returns false
    #4 While RaycastAll returns the expected element

    Since my usecase is as simple as "If pointer over UI, ignore game input", I would love to just rely on IsPointerOverGameObject(0), but to no avail.

    How come? Everything seems to have been set up properly.

    ---

    Using Unity 2022.3.5
     
  2. tomsseisums

    tomsseisums

    Joined:
    Oct 8, 2012
    Posts:
    37
    Found the reason.

    I was testing simultaneously on WebGL (Mobile/Touch) and in Editor (PC/Mouse). For WebGL to work, I needed to explicitly use pointerId=0, but that breaks on PC/Mouse setup, as PC doesn't register left click as pointerId=0, it registers it as pointerId=-1.

    I ended up double checking for cross-platform support:
    Code (CSharp):
    1. bool IsPointerOverUI()
    2. {
    3.     return EventSystem.current.IsPointerOverGameObject() // catch mouse setup
    4.            && EventSystem.current.IsPointerOverGameObject(0) // catch touch setup
    5. }