using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
public static T Instance
{
get
{
if (applicationIsQuitting)
{
Debug.LogWarning("[Singleton] Instance '" + typeof(T) +
"' already destroyed on application quit." +
" Won't create again - returning null.");
return null;
}
lock (_lock)
{
if (_instance == null)
{
_instance = (T)FindObjectOfType(typeof(T));
if (FindObjectsOfType(typeof(T)).Length > 1)
{
Debug.LogError("[Singleton] Something went really wrong " +
Unity继承MonoBehaviour的静态单例
最新推荐文章于 2024-01-30 15:43:31 发布
本文介绍了Unity中如何使用静态单例模式来管理MonoBehaviour类,确保在不绑定到游戏对象时能正常初始化并避免被删除。在需要使用时,可以直接通过T.Instance调用相关函数。
摘要由CSDN通过智能技术生成