Unity笔记之获取鼠标停留的UI和删除按键触发后引用、判断鼠标是否在UI上

您所在的位置:网站首页 鼠标事件接口 Unity笔记之获取鼠标停留的UI和删除按键触发后引用、判断鼠标是否在UI上

Unity笔记之获取鼠标停留的UI和删除按键触发后引用、判断鼠标是否在UI上

2023-09-22 05:41| 来源: 网络整理| 查看: 265

需求:鼠标放在UI上,需要获取这个UI物体,以方便进行其他操作。

百度学习了半天,最终拿了一个大哥(添加链接描述)的内容。本文仅作为个人笔记,建议大家直接去这大哥的博客看。不过我记得好像也可以通过继承unity内部的鼠标事件接口获取到物体,但是由于时间紧,等后面有时间或者想起了再加吧。

using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class NewBehaviourScript : MonoBehaviour { GameObject currentCanvas; void Start() { currentCanvas = gameObject; } void Update() { Debug.Log(GetUI(currentCanvas).name); } /// /// 获取鼠标停留处UI /// public static GameObject GetUI(GameObject canvas) { if (canvas.GetComponent() == null) return null; PointerEventData pointerEventData = new PointerEventData(EventSystem.current); pointerEventData.position = Input.mousePosition; GraphicRaycaster gr = canvas.GetComponent(); List results = new List(); gr.Raycast(pointerEventData, results); if (results.Count != 0) { return results[0].gameObject; } return null; } } 需求2:发现一个小问题,就是在使用UGUI的时候,如果点击了某个按钮之后不进行任何操作直接按键盘上的空格键就相当于再次点击了上一次点击过的那个按键。

所以要解决这个问题我们得把这个unity记录的地方在我们点击触发方法之后就把这个保存的按键给删除引用。

//在需要取消的地方加上这段就可以了 UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject(null, null);

加上这句代码就可以删除引用了。

需求3:判断鼠标是否在UI上 if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())//如果鼠标在UI上就返回 { return; }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3