using UnityEngine;
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
private static T _instance;
private static readonly object _lock = new object();
private static bool _applicationIsQuitting = false;
public static T Instance
{
get
{
if (_applicationIsQuitting) return null;
lock (_lock)
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
if (_instance == null)
{
GameObject singletonObject = new GameObject();
_instance = singletonObject.AddComponent<T>();
singletonObject.name = typeof(T).ToString() + " (Singleton)";
DontDestroyOnLoad(singletonObject);
Debug.Log($"An instance of {typeof(T).ToString()} is needed in the scene, so '{singletonObject.name}' was created with DontDestroyOnLoad.");
}
else
{
Debug.Log($"An instance of {typeof(T).ToString()} already exists in the scene so the object '{_instance.gameObject.name}' was used. The singleton template will destroy itself.");
}
}
return _instance;
}
}
}
protected virtual void Awake()
{
if (_instance == null)
{
_instance = this as T;
DontDestroyOnLoad(gameObject);
}
else if (_instance != this)
{
Destroy(gameObject);
}
}
protected virtual void OnDestroy()
{
_applicationIsQuitting = true;
}
protected virtual void OnApplicationQuit()
{
_applicationIsQuitting = true;
}
}
unity 标准单例类 MonoSingleton<T>
于 2025-01-16 15:23:59 首次发布
1092

被折叠的 条评论
为什么被折叠?



