You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity新Input System中点击UI时如何屏蔽游戏玩法输入?

Unity新Input System点击UI时屏蔽Point动作的最优方案

现有代码的问题

  • 混用旧Input System的Input.GetTouch(0) API,和新Input System的使用场景冲突,且仅支持单点触摸,适配性不足
  • 依赖UI标签判断UI元素,通用性差(默认UI元素无此标签,需手动添加)

最优解决方案

方法1:使用Unity内置的IsPointerOverGameObject(推荐)

利用Unity EventSystem的内置方法,结合新Input System的指针信息,直接判断当前指针是否落在UI元素上:

private bool IsPointerOverUI()
{
    // 获取当前指针ID:鼠标指针ID为-1,触摸指针为对应的touchId
    int pointerId = Pointer.current.pointerId.ReadValue();
    // 内置方法直接判断是否点击在UI上
    return EventSystem.current.IsPointerOverGameObject(pointerId);
}

在Point动作的回调中调用:

// 假设你的Point动作绑定了该回调
public void OnPointInput(InputAction.CallbackContext context)
{
    if (context.performed && !IsPointerOverUI())
    {
        // 执行游戏玩法逻辑
        Debug.Log("触发游戏输入");
    }
}

优势:

  • 无需手动编写射线检测,Unity内部已做性能优化
  • 自动适配鼠标、单点/多点触摸等多种输入方式
  • 无需依赖自定义标签,只要UI元素开启Raycast Target(默认开启)就会被检测到

方法2:自定义射线检测(灵活扩展)

如果需要更精细的控制(比如排除特定UI元素),可以自定义射线检测逻辑,但改用新Input System的指针位置:

private bool IsPointerOverUI()
{
    // 从新Input System获取当前指针位置
    Vector2 pointerPosition = Pointer.current.position.ReadValue();
    
    PointerEventData eventData = new PointerEventData(EventSystem.current)
    {
        position = pointerPosition
    };
    
    List<RaycastResult> raycastResults = new List<RaycastResult>();
    EventSystem.current.RaycastAll(eventData, raycastResults);
    
    // 可按需过滤结果,比如排除带有"IgnoreGameInput"标签的UI
    return raycastResults.Any(result => 
        !result.gameObject.CompareTag("IgnoreGameInput"));
}

方法3:全局标志位控制

给UI按钮添加点击事件,设置全局标志位,在游戏输入逻辑中判断:

  1. 定义全局变量:
public static bool IsUIPressed { get; private set; }
  1. 在UI按钮的OnClick事件中绑定方法:
public void OnUIButtonClicked()
{
    IsUIPressed = true;
    // 延迟重置标志位,避免后续输入被误屏蔽
    Invoke(nameof(ResetUIPressedFlag), 0.1f);
}

private void ResetUIPressedFlag()
{
    IsUIPressed = false;
}
  1. 在游戏输入回调中判断:
public void OnPointInput(InputAction.CallbackContext context)
{
    if (context.performed && !IsUIPressed)
    {
        // 执行游戏玩法逻辑
    }
}

注意:这种方式需要给所有需要屏蔽游戏输入的UI按钮绑定事件,适合UI数量较少的场景。

额外提示

  • 如果希望某些UI元素不屏蔽游戏输入,只需关闭该元素的Raycast Target选项(在Inspector的Image/Text等组件中)
  • 确保场景中已添加EventSystem和StandaloneInputModule(或新Input System的InputSystemUIInputModule),否则UI检测会失效

内容的提问来源于stack exchange,提问作者rino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 22:43:10