1. 程式人生 > >Unity UGUI獲取點選的UI

Unity UGUI獲取點選的UI

第一種方法

using UnityEngine.EventSystems;

public GameObject ClickObject()
    {
        PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        eventDataCurrentPosition.position = new Vector2
            (
#if UNITY_EDITOR
            Input.mousePosition.x, Input.mousePosition
.y #elif UNITY_ANDROID || UNITY_IOS Input.touchCount > 0 ? Input.GetTouch(0).position.x : 0, Input.touchCount > 0 ? Input.GetTouch(0).position.y : 0 #endif ); List<RaycastResult> results = new List<RaycastResult>(); EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
if (results.Count > 0) { return results[0].gameObject; } else { return null; } }

第二種方法

using UnityEngine.EventSystems;

public class NewBehaviourScript : MonoBehaviour, IPointerClickHandler
{

    public void OnPointerClick
(PointerEventData eventData) { print("當前點選的UI是:"+ eventData.pointerEnter); } }