UGUI - 判斷是否點擊在UI 上 Bug,IsPointerOverGameObject()在移動端檢測失敗
原文鏈接:這里寫鏈接內容
UGUI 提供了一個檢測是否點擊在UI上的方法 EventSystem.current.IsPointerOverGameObject(); 但是該方法在PC上檢測正常,結果拿到Android真機測試上,永遠檢測不到。
在網上找了一些大神的解決方案
using UnityEngine;using System.Collections;using System.Collections.Generic;using UnityEngine.UI;using UnityEngine.EventSystems;public class ClickIsOverUI { public static ClickIsOverUI Instance = new ClickIsOverUI(); public ClickIsOverUI() { } //方法一, 使用該方法的另一個重載方法,使用時給該方法傳遞一個整形參數 // 該參數即使觸摸手勢的 id // int id = Input.GetTouch(0).fingerId; public bool IsPointerOverUIObject(int fingerID) { return EventSystem.current.IsPointerOverGameObject(fingerID); } //方法二 通過UI事件發射射線 //是 2D UI 的位置,非 3D 位置 public bool IsPointerOverUIObject(Vector2 screenPosition) { //實例化點擊事件 PointerEventData eventDataCurrentPosition = new PointerEventData(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; } //方法三 通過畫布上的 GraphicRaycaster 組件發射射線 public bool IsPointerOverUIObject(Canvas canvas, Vector2 screenPosition) { //實例化點擊事件 PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current); //將點擊位置的屏幕坐標賦值給點擊事件 eventDataCurrentPosition.position = screenPosition; //獲取畫布上的 GraphicRaycaster 組件 GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent<GraphicRaycaster>(); List<RaycastResult> results = new List<RaycastResult>(); // GraphicRaycaster 發射射線 uiRaycaster.Raycast(eventDataCurrentPosition, results); return results.Count > 0; }}使用如下
using UnityEngine;using System.Collections;public class RayCastUI : MonoBehaviour { public Transform target; // Update is called once per frame void Update () {#if true //UNITY_ANDROID || UNITY_ipHONE if (Input.touchCount > 0) { //使用方法一:傳遞觸摸手勢 ID if (ClickIsOverUI.Instance.IsPointerOverUIObject(Input.GetTouch(0).fingerId)) { Debug.Log("方法一: 點擊在UI上"); if (target != null) { target.transform.rotation = Quaternion.Euler(new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, 0)); } } //使用方法二:傳遞觸摸手勢坐標 if (ClickIsOverUI.Instance.IsPointerOverUIObject(Input.GetTouch(0).position)) { Debug.Log("方法二: 點擊在UI 上"); } //使用方法三:傳遞畫布組件,傳遞觸摸手勢坐標 if (ClickIsOverUI.Instance.IsPointerOverUIObject(GetComponent<Canvas>(), Input.GetTouch(0).position)) { Debug.Log("方法三: 點擊在UI 上"); } }#endif }}經過測試上面三種方法均能成功
新聞熱點
疑難解答