温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

UGUI防止穿透和判断点击的是否是UI

发布时间:2020-02-29 07:53:18 来源:网络 阅读:8332 作者:速度速度撒 栏目:开发技术

年后刚上班,就有不幸的事情发生,项目界面要把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。

 希望大家能用的上。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI