鼠标点击发射射线,做3D游戏常用,但是点击UI时也会点击到场景中的物体,触发其他绑定事件,因此,需要点击UI时场景不触发射线检测EventSystem.current.IsPointerOverGameObject(),unity给出了解决方法。有一点要注意,UI上背景层和panel也都有射线检测,所以你会发现点击不了场景中的物体了,需要勾掉背景层的Raycast Target复选框。
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("点击到了UI");
return;
}
else
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
//int layerMask = 1 << 10;
//layerMask = ~layerMask;
if (Physics.Raycast(ray, out hitInfo))
{
Debug.DrawLine(ray.origin, hitInfo.point, Color.red);
go = hitInfo.collider.gameObject;
Debug.Log("碰到了:" + go.name);
}
}
}
当我把游戏打成包在手机端测试时,发现还是不行,这个方法在移动端不适用,于是给他加了一个判断
public bool IsPointerOverUIObject(int fingerID)
{
#if UNITY_EDITOR//如果是主机端,用unity的判断
return EventSystem.current.IsPointerOverGameObject();
#elif UNITY_ANDROID//如果是安卓端,用下面的判断
return EventSystem.current.IsPointerOverGameObject(fingerID);
#endif
}
在update中检测
void Update()
{
if (Input.touchCount > 0)//如果屏幕上的手指数大于0
{
//Debug.Log();
if (Input.GetMouseButtonDown(0) && isTouchMove && !IsPointerOverUIObject(Input.GetTouch(0).fingerId))
{
CheckPointer(Input.mousePosition);//没有点击到UI
}
}
else//如果屏幕上没有手指点击,用unity自带的判断条件
{
if (Input.GetMouseButtonDown(0) && isTouchMove && !EventSystem.current.IsPointerOverGameObject())
{
CheckPointer(Input.mousePosition);//没有点击到UI
}
}
}