Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find which object is EventSystem.current.IsPointerOverGameObject detecting?

Tags:

c#

unity3d

I am using EventSystem.current.IsPointerOverGameObject in a script and Unity returns True even though I would swear there is no UI/EventSystem object beneath the pointer.

How can I find information about the object the EventSystem is detecting?

like image 432
Peter Morris Avatar asked Aug 25 '16 16:08

Peter Morris


2 Answers

In your update() :

 if(Input.GetMouseButton(0))
 {
     PointerEventData pointer = new PointerEventData(EventSystem.current);
     pointer.position = Input.mousePosition;

     List<RaycastResult> raycastResults = new List<RaycastResult>();
     EventSystem.current.RaycastAll(pointer, raycastResults);

     if(raycastResults.Count > 0)
     {
         foreach(var go in raycastResults)
         {  
             Debug.Log(go.gameObject.name,go.gameObject);
         }
     }
 }
like image 139
Umair M Avatar answered Oct 23 '22 17:10

Umair M


I've stumbled upon this thread and wasn't quite happy with the solution provided, so here's another implementation to share:

public class StandaloneInputModuleV2 : StandaloneInputModule
{
    public GameObject GameObjectUnderPointer(int pointerId)
    {
        var lastPointer = GetLastPointerEventData(pointerId);
        if (lastPointer != null)
            return lastPointer.pointerCurrentRaycast.gameObject;
        return null;
    }

    public GameObject GameObjectUnderPointer()
    {
        return GameObjectUnderPointer(PointerInputModule.kMouseLeftId);
    }
}

Looking at the EventSystem's editor output showing names for the GameObjects, I decided that some functionality was already there and there should be means of using it. After diving into the opened source of the forementioned EventSystem and IsPointerOverGameObject (overrided in PointerInputModule), I thought it'll be easier to extend the default StandaloneInputModule.

Usage is simple, just replace the default one added on the scene with the EventSystem and reference in code like:

private static StandaloneInputModuleV2 currentInput;
private StandaloneInputModuleV2 CurrentInput
{
    get
    {
        if (currentInput == null)
        {
            currentInput = EventSystem.current.currentInputModule as StandaloneInputModuleV2;
            if (currentInput == null)
            {
                Debug.LogError("Missing StandaloneInputModuleV2.");
                // some error handling
            }
        }

        return currentInput;
    }
}

...

var currentGO = CurrentInput.GameObjectUnderPointer();
like image 25
Ilya Dvorovoy Avatar answered Oct 23 '22 16:10

Ilya Dvorovoy