溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

UGUI防止穿透和判斷點擊的是否是UI

發(fā)布時間:2020-02-29 07:53:18 來源:網(wǎng)絡(luò) 閱讀:8340 作者:速度速度撒 欄目:開發(fā)技術(shù)

年后剛上班,就有不幸的事情發(fā)生,項目界面要把NGUI推翻,用UGUI來做,真是蛋都碎了,但是沒辦法,在做的過程中遇UI穿透和點擊的是否是UI,查資料,問朋友,弄出來,跟大家分享:


1.UGUI自帶的防穿透代碼:

 if (EventSystem.current.IsPointerOverGameObject())
                    {
                        return;//為真,則點擊在UI上
                    }
   好像漏了點東西,沒有寫全,上面的只是Unity_Editor 下或者電腦上能運行,移動端是
  if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
                    {
                        return;//為真,則點擊在UI上
                    }    
      總結(jié):
   #if IPHONE || ANDROID
	if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
#else
	if (EventSystem.current.IsPointerOverGameObject())
#endif
		Debug.Log("當(dāng)前觸摸在UI上");
			
	else 
	       Debug.Log("當(dāng)前沒有觸摸在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;
    }

}

 第二種,我把它寫成了一個類,用到的調(diào)用就行

  public EventSystem eventSystem;
  public GraphicRaycaster graphicRaycaster;
  
   if (CheckUGUI.CheckGuiRaycastObjects(eventSystem, graphicRaycaster))
    return;//為真,就點擊的是UI。

 希望大家能用的上。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI