Unity 点击屏幕与UGUI的区分

    xiaoxiao2021-03-26  22

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

    经过测试上面三种方法均能成功

    转载请注明原文地址: https://ju.6miu.com/read-662151.html

    最新回复(0)