Unity UGUI判斷目前鼠標懸浮的是那類UI上

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class TestMouseUI : MonoBehaviour
{
    GameObject currentCanvas;
    // Start is called before the first frame update
    void Start()
    {
        currentCanvas = this.gameObject;
    }

    // Update is called once per frame
    void Update()
    {
        //if (EventSystem.current.IsPointerOverGameObject())
        //{
        //    Debug.Log("當前鼠標懸浮與UI之上");
        //}

        if (GetOverUI(currentCanvas) != null && GetOverUI(currentCanvas).tag.Equals("3DUI"))
        {
            Debug.Log("標籤爲3DUI的UI");
        }

        if (GetOverUI(currentCanvas) != null && GetOverUI(currentCanvas).tag.Equals("UI"))
        {
            Debug.Log("標籤爲2DUI");
        }
    }

    /// <summary>
    /// 獲取鼠標停留處UI
    /// </summary>
    /// <param name="canvas"></param>
    /// <returns>UI物體</returns>
    public static GameObject GetOverUI(GameObject canvas)
    {
        if (canvas.GetComponent<GraphicRaycaster>() == null) return null;
        PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
        pointerEventData.position = Input.mousePosition;
        GraphicRaycaster gr = canvas.GetComponent<GraphicRaycaster>();
        List<RaycastResult> results = new List<RaycastResult>();
        gr.Raycast(pointerEventData, results);
        if (results.Count != 0)
        {
            return results[0].gameObject;
        }
        return null;
    }
}

給需要分類的UI加上相應的標籤即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章