1、!EventSystem.current.IsPointerOverGameObject()
2、主相机挂在 PhysicsRaycaster 与3d物体交互、上述不太好使
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public static class InputExtension
{
/// <summary>
/// 判断Touch 按下时是否打到了 UI 组件。
/// Determine whether the UI component is hit when touch begin.
/// </summary>
public static bool IsRaycastUI(this Touch touch, string filter = "") => Raycast(touch.position, filter);
/// <summary>
/// 判断指定按键按下时是否打到了 UI 组件。
/// Determine whether the UI component is hit when the specified mouse button is pressed.
/// </summary>
public static bool IsRaycastUI(string filter = "") => Raycast(Input.mousePosition, filter);
private static PointerEventData pointerEventData;
private static List<RaycastResult> list;
/// <summary>
/// 执行射线检测确认是否打到了UI
/// </summary>
/// <param name="position">Touch 或者 光标所在的位置</param>
/// <param name="filterPrefix">希望忽略的UI,有些情况下,从UI上开始拖拽也要旋转视野,如手游CF的狙击开镜+拖拽 ,注意:优先判断底层节点</param>
/// <returns></returns>
static bool Raycast(Vector2 position, string filterPrefix)
{
if (!EventSystem.current/* && !EventSystem.current.IsPointerOverGameObject()*/) return false;// 事件系统有效且射线有撞击到物体
if (pointerEventData == null)
pointerEventData = new PointerEventData(EventSystem.current);
if (list == null)
list = new List<RaycastResult>();
pointerEventData.pressposition = position;
pointerEventData.position = position;
EventSystem.current.RaycastAll(pointerEventData, list);
return list.Count > 0 && list[0].module is UnityEngine.UI.GraphicRaycaster/* && !list[0].gameObject.name.StartsWith(filterPrefix)*/;
}
}