年后刚上班,就有不幸的事情发生,项目界面要把NGUI推翻,用UGUI来做,真是蛋都碎了,但是没办法,在做的过程中遇UI穿透和点击的是否是UI,查资料,问朋友,弄出来,跟大家分享:
1.UGUI自带的防穿透代码:
if (EventSystem.current.IsPointerOverGameObject())
{
return;//为真,则点击在UI上
}
好像漏了点东西,没有写全,上面的只是Unity_Editor 下或者电脑上能运行,移动端是
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
{
return;//为真,则点击在UI上
}
总结:
#if IPHONE || ANDROID
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
#else
if (EventSystem.current.IsPointerOverGameObject())
#endif
Debug.Log("当前触摸在UI上");
else
Debug.Log("当前没有触摸在UI上");
2.查资料,自己写了一个判断
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using UnityEngine.UI;
public class CheckUGUI : MonoBehaviour {
public static bool CheckGuiRaycastObjects(EventSystem eventSystem, GraphicRaycaster graphicRayCaster)
{
PointerEventData eventData = new PointerEventData(eventSystem);
#if UNITY_EDITOR
eventData.pressPosition = Input.mousePosition;
eventData.position = Input.mousePosition;
#endif
#if UNITY_ANDROID || UNITY_IPHONE
if (Input.touchCount > 0)
{
eventData.pressPosition = Input.GetTouch(0).position;
eventData.position = Input.GetTouch(0).position;
}
#endif
List<RaycastResult> list = new List<RaycastResult>();
graphicRayCaster.Raycast(eventData, list);
return list.Count > 0;
}
}
第二种,我把它写成了一个类,用到的调用就行
public EventSystem eventSystem;
public GraphicRaycaster graphicRaycaster;
if (CheckUGUI.CheckGuiRaycastObjects(eventSystem, graphicRaycaster))
return;//为真,就点击的是UI。
希望大家能用的上。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。