Unity判断点击对象
UI的点击响应是Unity中最基本的操作,UI响应点击事件,在场景中必须有EventSystem和InputModel(通常为StandaloneInputModule)脚本,UI对象必须勾选RaycastTarget。如果Canvas的Render Mode是World Space的话,UI的z轴方向必须和相机朝向一样(不超过90°)!(之前做了个场景,放置了类似广告牌的UI,在场景中由于图片是对称的,不知道什么时候操作翻转了,一直点不到,还看了半天代码...)
有时我们需要判断屏幕上是否点击到了UI对象,可以用过EventSystem的IsPointerOverGameObject方法判断。鼠标点击使用以下代码:
void Update() { if (Input.GetMouseButtonDown(0)) { if (EventSystem.current.IsPointerOverGameObject()) { Debug.Log("Clicked on the UI"); } } }
手机触碰使用以下代码
void Update()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) { if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
{ Debug.Log("Touched the UI"); } }
}
以上的方式只能知道是否点击UI,但是不能判断具体点击到哪个,如果想知道具体点击到的UI对象可以使用,以下代码。
PointerEventData m_Data = null; List<RaycastResult> results = new List<RaycastResult>(); void Start() { m_Data = new PointerEventData(EventSystem.current); } void Update() { if (Input.GetMouseButtonDown(0)) { m_Data.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y); EventSystem.current.RaycastAll(m_Data, results); for (int i = 0; i < results.Count; ++i) { Debug.Log(results[i].gameObject.name); } } }
如果需要判断点击场景物体对象,可以使用射线,对象必须包含Collider组件(包括BoxCollider,SphereCollider等),代码如下。
void Update() { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { Debug.Log(hit.transform.name); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?