using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
/// <summary>
/// 全局Click检测
/// </summary>
public class ClickEvent : MonoBehaviour
{
private RaycastHit ObjHit;
private Ray CustomRay;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
#if UNITY_ANDROID || UNITY_IPHONE
//移动端判断如下
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
#else
//PC端判断如下
if (EventSystem.current.IsPointerOverGameObject())
#endif
{
Debug.Log("当前点击在UI上" + EventSystem.current.currentSelectedGameObject);
}
else
{
//从摄像机发出一条射线,到点击的坐标
CustomRay = Camera.main.ScreenPointToRay(Input.mousePosition);
//显示一条射线,只有在scene视图中才能看到
Debug.DrawLine(CustomRay.origin, ObjHit.point, Color.red, 2);
if (Physics.Raycast(CustomRay, out ObjHit, 100))
{
if (ObjHit.collider.gameObject != null)
{
Debug.Log("Click Object:" + ObjHit.collider.gameObject);
}
}
else
{
Debug.Log("Click Null");
}
}
}
}
}
unity 点击是UI 还是GameObj
最新推荐文章于 2024-04-18 22:35:54 发布
本文介绍了一个Unity中的脚本,用于实现全局的鼠标点击事件检测。该脚本能够判断点击是否发生在UI元素上,若不在UI上,则通过射线投射来检测场景中的物体,并输出被点击物体的信息。
1万+

被折叠的 条评论
为什么被折叠?



