如何在Unity New Input System中点击UI元素时忽略鼠标输入?
解决Unity新输入系统中鼠标UI检测的警告问题
问题原因
EventSystem.current.IsPointerOverGameObject()在InputAction回调中调用时,会查询上一帧的UI交互状态,不仅可能导致判断不准确,还会触发官方警告。这是因为新输入系统的回调时机与EventSystem的帧内事件处理流程不同步。
解决方案1:缓存UI状态到Update中
在每帧Update里提前检测UI状态并缓存,回调中直接使用缓存值,避免跨帧问题:
private bool _isPointerOverUI; private void Update() { // 每帧更新当前UI状态 _isPointerOverUI = EventSystem.current.IsPointerOverGameObject(); } private void OnEnable() { mouseClick.Enable(); mouseClick.performed += MousePressed; } private void OnDisable() { mouseClick.performed -= MousePressed; mouseClick.Disable(); } private void MousePressed(InputAction.CallbackContext context) { // 使用缓存的当前帧UI状态 if (_isPointerOverUI) return; Ray ray = _playerCam.ScreenPointToRay(Mouse.current.position.ReadValue()); RaycastHit hit; // 你的射线检测逻辑... }
解决方案2:手动触发UI射线检测
通过GraphicRaycaster主动对当前鼠标位置做UI射线检测,直接获取当前帧的交互结果,无需依赖Update:
private GraphicRaycaster _graphicRaycaster; private EventSystem _eventSystem; private void Awake() { // 获取场景中的GraphicRaycaster(通常挂在Canvas上) _graphicRaycaster = FindObjectOfType<GraphicRaycaster>(); _eventSystem = EventSystem.current; } // 自定义UI检测方法 private bool IsPointerOverUI() { // 创建当前帧的指针事件数据 PointerEventData pointerEventData = new PointerEventData(_eventSystem); pointerEventData.position = Mouse.current.position.ReadValue(); List<RaycastResult> raycastResults = new List<RaycastResult>(); // 执行UI射线检测 _graphicRaycaster.Raycast(pointerEventData, raycastResults); // 如果有检测结果,说明鼠标在UI上 return raycastResults.Count > 0; } private void OnEnable() { mouseClick.Enable(); mouseClick.performed += MousePressed; } private void OnDisable() { mouseClick.performed -= MousePressed; mouseClick.Disable(); } private void MousePressed(InputAction.CallbackContext context) { if (IsPointerOverUI()) return; Ray ray = _playerCam.ScreenPointToRay(Mouse.current.position.ReadValue()); RaycastHit hit; // 你的射线检测逻辑... }
注意事项
- 方案2需要确保场景中存在带
GraphicRaycaster组件的Canvas(所有可交互UI都在该Canvas下)。 - 两种方案都能避免警告,且保证UI状态判断的准确性,可根据项目需求选择。
内容的提问来源于stack exchange,提问作者New One
相关产品推荐
相关产品推荐

