年后刚上班,就有不幸的事情发生,项目界面要把NGUI推翻,用UGUI来做,真是蛋都碎了,但是没办法,在做的过程中遇UI穿透和点击的是否是UI,查资料,问朋友,弄出来,跟大家分享:


1.UGUI自带的防穿透代码:

if(EventSystem.current.IsPointerOverGameObject()){return;//为真,则点击在UI上}好像漏了点东西,没有写全,上面的只是Unity_Editor下或者电脑上能运行,移动端是if(EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)){return;//为真,则点击在UI上}总结:#ifIPHONE||ANDROIDif(EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))#elseif(EventSystem.current.IsPointerOverGameObject())#endifDebug.Log("当前触摸在UI上");elseDebug.Log("当前没有触摸在UI上");

2.查资料,自己写了一个判断

usingUnityEngine;usingSystem.Collections;usingUnityEngine.EventSystems;usingSystem.Collections.Generic;usingUnityEngine.UI;publicclassCheckUGUI:MonoBehaviour{publicstaticboolCheckGuiRaycastObjects(EventSystemeventSystem,GraphicRaycastergraphicRayCaster){PointerEventDataeventData=newPointerEventData(eventSystem);#ifUNITY_EDITOReventData.pressPosition=Input.mousePosition;eventData.position=Input.mousePosition;#endif#ifUNITY_ANDROID||UNITY_IPHONEif(Input.touchCount>0){eventData.pressPosition=Input.GetTouch(0).position;eventData.position=Input.GetTouch(0).position;}#endifList<RaycastResult>list=newList<RaycastResult>();graphicRayCaster.Raycast(eventData,list);returnlist.Count>0;}}

第二种,我把它写成了一个类,用到的调用就行

publicEventSystemeventSystem;publicGraphicRaycastergraphicRaycaster;if(CheckUGUI.CheckGuiRaycastObjects(eventSystem,graphicRaycaster))return;//为真,就点击的是UI。

希望大家能用的上。