public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
private bool isInit = false;
public static T Instance
{
get => instance ??= new Lazy<GameObject>(new GameObject($"{typeof(T).Name}")).Value.AddComponent<T>();
}
protected virtual void Awake()
{
if (instance != null) Destroy(gameObject);
else DontDestroyOnLoad(gameObject);
}
internal void Init()
{
if(isInit == false)
{
InnerInit();
isInit = true;
}
}
protected virtual void InnerInit() { }
}
Unity 持久单例SingletonMonoBehaviour
于 2024-10-11 12:56:09 首次发布
303

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



