1. 程式人生 > >Unity 點選螢幕與UGUI的區分

Unity 點選螢幕與UGUI的區分

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
    }
}

經過測試上面三種方法均能成功