Unity 獲取遊戲UI根節點

Unity遊戲開發過程中,經常需要獲取Canvas來獲取UI界面的根節點,方便實例化UI面板的位置,所以就自己總結了一個

 

using System;
using UnityEngine;

public class GameUtils : MonoBehaviour
{
    private GameObject uiRoot = null;

    private static GameUtils _instance;

    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }

    public static GameUtils Instance()
    {
        if (_instance == null)
        {
            _instance = new GameUtils();
        }
        return _instance;
    }

    public GameObject UiRoot
    {
        get
        {
            return GetUIRoot();
        }
    }

    private GameObject GetUIRoot()
    {
        try
        {
            if (uiRoot != null)
            {
                return uiRoot;
            }
            if (FindObjectOfType<Canvas>() != null)
            {
                uiRoot = FindObjectOfType<Canvas>().gameObject;
                return uiRoot;
            }
            else
            {
                uiRoot = GameObject.Find("Canvas").gameObject;
                return uiRoot;
            }
        }
        catch (Exception e)
        {
            Debug.Log("獲取根節點失敗原因:" + e);
        }
        return null;
    }
}

 

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