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)*/;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值