解决UI与3d物体的事件响应问题
1.3D物体也可以使用EventSystems里的接口,需要相机上添加PhysicsRaycaster组件。
2.UI响应事件向下传递:
//向下传递UI响应事件 private void PassdownEvent(PointerEventData eventData, ExecuteEvents.EventFunction<IPointerClickHandler> function) { List<RaycastResult> results = new List<RaycastResult>(); EventSystem.current.RaycastAll(eventData, results); //获得本次点击的所有物体 for (int i = 0; i < results.Count; i++) { //Debug.Log(results[i].gameObject.name); if (results[i].gameObject != gameObject) //移除自己 { ExecuteEvents.Execute(results[i].gameObject, eventData, function); } } }
3.当鼠标点击在UI上时,不响应鼠标点击事件
private GraphicRaycaster uiRaycaster;
private void Update() { //当鼠标点在UI上时,不响应鼠标点击事件 if (Input.GetMouseButtonDown(0) && !IsPointClickUI()) { //......... } }//判断是否点击到ui了,返回true是点击到ui了,反之没有 public bool IsPointClickUI() { PointerEventData eventData = new PointerEventData(EventSystem.current); eventData.position = Input.mousePosition; eventData.pressPosition = Input.mousePosition; List<RaycastResult> resultAppendList = new List<RaycastResult>(); uiRaycaster.Raycast(eventData, resultAppendList); return resultAppendList.Count > 0; }