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 ui