Unity 怎样判断鼠标是否在哪个UI上(两种方法)

45 篇文章 10 订阅
43 篇文章 1 订阅
  • 第一种

     可以得到UI,再根据名字判断是不是自己自己要点击的UI
     其中参数canvas拖入此UI的canvas
    
    	/// <summary>
        /// 获取鼠标停留处UI
        /// </summary>
        /// <param name="canvas"></param>
        /// <returns></returns>
        public GameObject GetOverUI(GameObject canvas)
        {
            PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
            pointerEventData.position = Input.mousePosition;
            GraphicRaycaster gr = canvas.GetComponent<GraphicRaycaster>();
            List<RaycastResult> results = new List<RaycastResult>();
            gr.Raycast(pointerEventData, results);
            if (results.Count != 0)
            {
                return results[0].gameObject;
            }
            return null;
        }
    
    
  • 第二种

     rect 为要判断的那个UI的RectTransform
    
    bool isUI = RectTransformUtility.RectangleContainsScreenPoint(rect, Input.mousePosition)
    

    补充:Unity中判断鼠标或者手指是否点击在UI上(UGUI)

    在Unity场景中,有时UI和游戏角色都需要响应触摸事件,如果同时响应可能就会出现点击UI的时候影响到了游戏角色。所以我们需要对所点击到的东西做判断,
    这里使用UGUI系统自带的方法和射线检测的方式,判断是否点击到UI上:

  • 第一种方法,直接在Update中判断:

    void Update()
        {      
            //判断是否点击UI
            if (Input.GetMouseButtonDown(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
            {
                //移动端
                if (Application.platform == RuntimePlatform.Android ||
                            Application.platform == RuntimePlatform.IPhonePlayer)
                {
                    int fingerId = Input.GetTouch(0).fingerId;
                    if (EventSystem.current.IsPointerOverGameObject(fingerId))
                    {
                        Debug.Log("点击到UI");                    
                    }
                }
                //其它平台
                else
                {
                    if (EventSystem.current.IsPointerOverGameObject())
                    {
                        Debug.Log("点击到UI");                    
                    }
                }
            }
    
    
  • 第二种方式:射线检测

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.EventSystems; 
    public class NewBehaviourScript : MonoBehaviour
    {
        // Update is called once per frame
        void Update()
        {
            //移动端
            if (Application.platform == RuntimePlatform.Android ||
                        Application.platform == RuntimePlatform.IPhonePlayer)
            {
                if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
                {
                    if (IsPointerOverGameObject(Input.GetTouch(0).position))
                    {
                        Debug.Log("点击到UI");
                    }
                }            
            }
            //其它平台
            else
            {
                if(Input.GetMouseButtonDown(0))
                {
                    if (IsPointerOverGameObject(Input.mousePosition))
                    {
                        Debug.Log("点击到UI");
                    }
                }            
            }
        }
     
        /// <summary>
        /// 检测是否点击UI
        /// </summary>
        /// <param name="mousePosition"></param>
        /// <returns></returns>
        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;
            }
        }
    }
    
  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用以下方法判断鼠标是否UI元素上: 1. 使用EventSystem的IsPointerOverGameObject()方法判断鼠标是否悬停在UI元素上: ```C# if (EventSystem.current.IsPointerOverGameObject()) { // 鼠标UI上 } else { // 鼠标不在UI上 } ``` 2. 获取鼠标在屏幕上的位置,然后使用RectTransformUtility的ScreenPointToLocalPointInRectangle()方法将屏幕坐标转换为UI元素内部的本地坐标,再判断本地坐标是否UI元素的范围内: ```C# // 获取鼠标在屏幕上的位置 Vector2 mousePos = Input.mousePosition; // 判断鼠标在哪个UI元素上 RectTransform rectTransform = null; if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, mousePos, canvas.worldCamera, out Vector2 localPos)) { // 获取鼠标在哪个UI元素上 rectTransform = GetRectTransformUnderPoint(canvas, localPos); } if (rectTransform != null) { // 鼠标UI元素上 } else { // 鼠标不在UI元素上 } // 获取鼠标所在的UI元素 private RectTransform GetRectTransformUnderPoint(Canvas canvas, Vector2 localPos) { GraphicRaycaster gr = canvas.GetComponent<GraphicRaycaster>(); PointerEventData ped = new PointerEventData(null); ped.position = localPos; List<RaycastResult> results = new List<RaycastResult>(); gr.Raycast(ped, results); if (results.Count > 0) { return results[0].gameObject.GetComponent<RectTransform>(); } return null; } ``` 以上两种方法都可以判断鼠标是否UI元素上,具体使用哪种方法取决于你的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

unity_YTWJJ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值