【问题标题】:Warning when calling IsPointerOverGameObject after updating Unity; is there an alternative?更新 Unity 后调用 IsPointerOverGameObject 时出现警告;有其他选择吗?
【发布时间】:2022-08-20 15:55:30
【问题描述】:

我有一个InputAction 回调,我正在记录玩家点击屏幕的位置,但是只要如果点击不在 UI 元素上。这是我的代码

private void OnPress(InputAction.CallbackContext context)
{
    if (!EventSystem.current.IsPointerOverGameObject())
    {
        this.pressPosition = Mouse.current.position.ReadValue();
    }
}

这一直在正常工作。但是,我最近更新了 Unity 版本,现在每次单击游戏中的某个位置时都会收到此警告:

Calling IsPointerOverGameObject() from within event processing (such as from InputAction callbacks) 
will not work as expected; it will query UI state from the last frame

根据changelog,此警告是在对输入系统的更新中添加的。

当玩家点击屏幕而没有收到此警告时,有没有办法确定鼠标是否在 UI 上?

    标签: unity3d


    【解决方案1】:

    我如何解决它是通过将那段逻辑移动到 Unity 的更新函数:

    private void Update()
    {
      if (Mouse.current.leftButton.wasPressedThisFrame)
      {
        if (EventSystem.current.IsPointerOverGameObject(PointerInputModule.kMouseLeftId))
          // was pressed on GUI
        else
          // was pressed outside GUI
      }
    }
    

    您仍然可以继续使用输入系统,即在取消时:

    private void OnPress(InputAction.CallbackContext context)
    {
      if (context.canceled)
        // Left mouse is no longer pressed. You can do something within the input system notification.
    }
    

    【讨论】:

      【解决方案2】:
       private bool pressControl = false;
       private void Update()
       {
          if (Mouse.current.leftButton.wasPressedThisFrame)
              pressControl =!EventSystem.current.IsPointerOverGameObject(PointerInputModule.kMouseLeftId);
       }
      
       void selector(InputAction.CallbackContext context)
       {
          if (!pressControl) return;
          pressControl = false;
      
          Vector3 position = new Vector3(mausePositionEvent.ReadValue<Vector2>().x, mausePositionEvent.ReadValue<Vector2>().y, 0);
          Ray ray = Camera.main.ScreenPointToRay(position);
          RaycastHit hit;
          if (!Physics.Raycast(ray, out hit)) return;
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-23
        • 1970-01-01
        • 2023-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-01
        相关资源
        最近更新 更多