unity 鼠标判断是否在ui上

第一种:

 if (EventSystem.current.IsPointerOverGameObject())
	{
       Debug.Log("点击到UI");
    }
               

第二种:

void Update()
    {
        if (IsPointerOverGameObject(Input.mousePosition))
        {
            Debug.Log("点击到UI");
        }
    }
    
    private bool IsPointerOverGameObject(Vector2 mousePosition)
    {       
        //创建一个点击事件
        PointerEventData eventData = new PointerEventData(EventSystem.current);
        eventData.position = mousePosition;
        List<RaycastResult> raycastResults = new List<RaycastResult>();
        //向点击位置发射一条射线,检测是否点击UI
        EventSystem.current.RaycastAll(eventData, raycastResults);
        if (raycastResults.Count > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
               

上面两种方法鼠标进入带有collider的3d物体后也会判定为在ui上所以改为第三种

第三种:


 		private GraphicRaycaster graphicRaycaster;
        private EventSystem eventSystem;
        private PointerEventData eventData;
        private bool init = false;

		void Updata
		{
			Debu.Log(IsOnUIElement());

		}
 

        void Init()
        {
            if (!init)
            {
                graphicRaycaster = GameObject.Find("UI").GetComponent<GraphicRaycaster>();
                //                                  ↑这里要根据你自己的项目自己找canvas上的GraphicRaycaster
                eventSystem = EventSystem.current;
                eventData = new PointerEventData(eventSystem);
                init = true;
            }
        }
        
        /// <summary>
        /// 是否在UI上
        /// </summary>
        /// <returns></returns>
        public bool IsOnUIElement()
        {
            Init();
            if (graphicRaycaster == null)
            {
                Debug.Log("无GraphicRaycaster,有问题");
                return false;
            }
            eventData.pressPosition = Input.mousePosition;
            eventData.position = Input.mousePosition;
            List<RaycastResult> list = new List<RaycastResult>();
            graphicRaycaster.Raycast(eventData, list);
            foreach (var temp in list)
            {
                if (temp.gameObject.layer.Equals(5)) return true;
            }
            return false;
        }

原文链接:https://blog.csdn.net/qq_33994566/article/details/106069521
               
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值