行业知识
Unity 检测鼠标是否在UI上的方法
2026-11-12 23:35:09
来源:互联网转载
��整理一下:
()1.官方提供的API:
void LateUpdate() { //该方法过于简单粗暴,所有有些不足之处,列如:1.检测不到返回细节,2.场景有3d可点击物体,也会杯当作UI 检测(这点可能不准确,需要测试) //方法用于判断鼠标是否点击在UI上。这个方法通过检查 //UI元素的Raycast Target属性来确定是否在UI元素上。如果UI元素的Raycast Target属性被勾选, //那么当鼠标点击在该UI元素上时,该方法将返回true;否则,返回false。 if (EventSystem.current.IsPointerOverGameObject()) { Debug.Log("点击了UI"); } } 2.直接通过检测UIcanvas 的GraphicRaycaster来判断(直接杜绝检测到场景中物体)
() /// /// 获取鼠标停留处UI /// /// /// public bool GetOverUI(GameObject canvas) { PointerEventData pointerEventData = new PointerEventData(EventSystem.current); pointerEventData.position = Input.mousePosition; GraphicRaycaster gr = canvas.GetComponent(); List results = new List(); gr.Raycast(pointerEventData, results); Debug.Log("results.Count=" + results.Count); // return results[0].gameObject.name; if (results.Count != 0) { return false; } else { return true; } } 3.和官方提供的差不多
void Update() { if (Input.GetMouseButtonDown(0)) { if (IsPointerOverGameObject(Input.mousePosition)) { Debug.Log("点击到UI"); } else { Debug.Log("点击到空白"); choiceTime.StartChoiceTime(); } } } /// /// 检测是否点击UI /// /// 鼠标位置 /// private bool IsPointerOverGameObject(Vector2 mousePosition) { //创建一个点击事件 PointerEventData eventData = new PointerEventData(EventSystem.current); eventData.position = mousePosition; List raycastResults = new List(); //向点击位置发射一条射线,检测是否点击UI EventSystem.current.RaycastAll(eventData, raycastResults); if (raycastResults.Count > 0)//大于0 说明 有UI { return true; } else { return false; } }//方法 扩展/// /// 检测是否点击UI /// /// 鼠标位置 /// private bool IsPointerOverGameObject(Vector2 mousePosition) { //创建一个点击事件 PointerEventData eventData = new PointerEventData(EventSystem.current); eventData.position = mousePosition; List raycastResults = new List(); //向点击位置发射一条射线,检测是否点击UI EventSystem.current.RaycastAll(eventData, raycastResults); if (raycastResults.Count > 0) { Debug.Log("raycastResults[0].gameObject.name=" + raycastResults[0].gameObject.name); if (raycastResults[0].gameObject.name == "RawImage")//判断是否 是 自己要点击的UI { return true; } else { return false; } } else { return false; } }
上一篇:浪潮服务器怎么进阵列?
下一篇:hmcl外置登录怎么进服务器?