unity 判断鼠标或Touch在UI上

1、!EventSystem.current.IsPointerOverGameObject()
2、主相机挂在 PhysicsRaycaster 与3d物体交互、上述不太好使

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public static class InputExtension
{
    /// 
    /// 判断Touch 按下时是否打到了 UI 组件。
    /// Determine whether the UI component is hit when touch begin.
    /// 
    public static bool IsRaycastUI(this Touch touch, string filter = "") => Raycast(touch.position, filter);

    /// 
    /// 判断指定按键按下时是否打到了 UI 组件。
    /// Determine whether the UI component is hit when the specified mouse button is pressed.
    /// 
    public static bool IsRaycastUI(string filter = "") => Raycast(Input.mousePosition, filter);

    private static PointerEventData pointerEventData;
    private static List<RaycastResult> list;

    /// 
    /// 执行射线检测确认是否打到了UI
    /// 
    /// Touch 或者 光标所在的位置
    /// 希望忽略的UI,有些情况下,从UI上开始拖拽也要旋转视野,如手游CF的狙击开镜+拖拽 ,注意:优先判断底层节点
    /// 
    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)*/;
    }
}

你可能感兴趣的:(ui,unity,游戏引擎)