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
{
    /// <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)*/;
    }
}

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...