void Update() { if(IsTouchedUI()) { Debug.Log("當前觸摸在UI上"); } else { Debug.Log("當前沒有觸摸在UI上"); } } void OnMouseDown() { if(IsTouchedUI()) { Debug.Log("當前觸摸在UI上"); } else { Debug.Log("當前沒有觸摸在UI上"); } } bool IsTouchedUI() { bool touchedUI = false; if (Application.isMobilePlatform) { if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) { touchedUI = true; } } else if (EventSystem.current.IsPointerOverGameObject()) { touchedUI = true; } return touchedUI; }
現在我們只需要在沒有觸摸UI的時候進行射線檢測或者其他操作就行了。
在Android機上進行UI防止穿透,寫了一套全平臺通用的代碼如下。
void OnMouseDown() { if(!IsPointerOverGameObject(Input.mousePosition)) { //沒有點擊UI } } public bool IsPointerOverGameObject(Vector2 screenPosition) { //實例化點擊事件 PointerEventData eventDataCurrentPosition = new PointerEventData(UnityEngine.EventSystems.EventSystem.current); //將點擊位置的屏幕坐標賦值給點擊事件 eventDataCurrentPosition.position = new Vector2(screenPosition.x, screenPosition.y); List<RaycastResult> results = new List<RaycastResult>(); //向點擊處發射射線 EventSystem.current.RaycastAll(eventDataCurrentPosition, results); return results.Count > 0; }
我們將IsPointerOverGameObject統一修改為自己重載的方法,然后傳進去Input.mouseposition 就可以了。
?
?
?
原文鏈接:http://blog.csdn.net/yupu56/article/details/54561553