如何找到哪个对象是EventSystem.current.IsPointerOverGameObject检测?

Pet*_*ris 4 c# unity-game-engine

我在脚本中使用EventSystem.current.IsPointerOverGameObject,Unity返回True,即使我发誓指针下面没有UI/EventSystem对象.

如何查找有关EventSystem正在检测的对象的信息?

Uma*_*r M 10

在你的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);
         }
     }
 }
Run Code Online (Sandbox Code Playgroud)


小智 6

我偶然发现了这个线程,对提供的解决方案不太满意,所以这里有另一个实现要分享:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

查看显示游戏对象名称的 EventSystem 编辑器输出,我决定某些功能已经存在并且应该有使用它的方法。在深入了解上述和(在 中覆盖)的开源之后,我认为扩展默认的.EventSystemIsPointerOverGameObjectPointerInputModuleStandaloneInputModule

用法很简单,只需将场景中添加的默认替换为 EventSystem 并在代码中引用,例如:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

...

var currentGO = CurrentInput.GameObjectUnderPointer();
Run Code Online (Sandbox Code Playgroud)