主要涉及API:
EventSystem.current.IsPointerOverGameObject()
EventSystem.current.IsPointerOverGameObject(Touch.fingerId)
//鼠标点击
if (EventSystem.current.IsPointerOverGameObject())
{
//TODO:点击在了UI上
}
//手机上触屏模式需要传入手指ID
//经测试,始终返回false,未知原因
if (EventSystem.current.IsPointerOverGameObject(touch.fingerId))
{
//TODO:点击在了UI上
}
同时再加上射线检测辅助判断
//放回值list.Count > 0 表示点击到了UI
bool CheckGuiRaycastObjects()
{
PointerEventData eventData = new PointerEventData(es);
eventData.pressPosition = Input.mousePosition;//touch.position
eventData.position = Input.mousePosition;//touch.position
var results= new List<RaycastResult>();
curCanvas.GetComponent<GraphicRaycaster>().Raycast(eventData, results);
//EventSystem.current.RaycastAll(eventData, results); //使用此方式也可
return list.Count > 0;
}
完整代码:
void CheckClickUI()
{
#if ((UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR)
//Touch
int touchCount = Input.touchCount;
if (touchCount == 1)
{
Touch t = Input.GetTouch(0);
if(t.phase == TouchPhase.Began)
{
//手机返回值异常,采用||
if (EventSystem.current.IsPointerOverGameObject (t.fingerId) || CheckGuiRaycastObjects(t.position))
{
//点击到UI
}
}
}
#else
//Mouse
if (Input.GetMouseButton(0))
{
//PC返回值正常,双重判定
if (EventSystem.current.IsPointerOverGameObject() && CheckGuiRaycastObjects(Input.mousePosition))
{
//点击到UI
}
}
#endif
}
bool CheckGuiRaycastObjects(Vector3 position)
{
PointerEventData eventData = new PointerEventData(EventSystem.current);
eventData.pressPosition = new Vector2(position.x, position.y);
eventData.position = new Vector2(position.x, position.y);
var results= new List<RaycastResult>();
//curCanvas.GetComponent<GraphicRaycaster>().Raycast(eventData, results);//使用canvas进行检测也可
EventSystem.current.RaycastAll(eventData, results);
return results.Count > 0;
}
遇到的问题:
个人测试在手机上 EventSystem.current.IsPointerOverGameObject(Touch.GetTouch(0).fingerId) 始终返回的是false,不知是什么原因,希望有知道的朋友可以留言告知一下,再次感谢!
暂时做法是,手机上当EventSystem.current.IsPointerOverGameObject返回false时,再执行射线再次检测是否点击到UI