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中的泛型单例脚本工具