Files
PrinceOfGlory/Assets/Scripts/XRCore/Base/MonoSingleton.cs
kridoo 6e91a0c7f0 111
2025-09-15 17:32:08 +08:00

52 lines
1.4 KiB
C#

using UnityEngine;
namespace BigSpace.XRCore.Base
{
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
private static T _instance;
private static readonly object _lock = new object();
public static T Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
_instance = FindObjectOfType<T>();
if (_instance == null)
{
GameObject singletonObject = new GameObject(typeof(T).Name);
_instance = singletonObject.AddComponent<T>();
DontDestroyOnLoad(singletonObject);
}
}
}
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()
{
if (_instance == this)
{
_instance = null;
}
}
}
}