欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity 获取游戏UI根节点

程序员文章站 2022-03-02 11:48:06
...

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

 

相关标签: Unity