namespaceUnityToolkit { publicclassLazySingleton<T> : IDisposablewhereT : new() { privatestaticreadonly Lazy<T> s_instance = new Lazy<T>(() => { T t = new T(); if (t is IOnInit init) { init.OnInit(); }
return t; });
publicstatic T Singleton => s_instance.Value;
publicvirtualvoidDispose() { if (Singleton is IDisposable disposable) { disposable.Dispose(); } } } }
publicstatic T Singleton { get { // 如果T是仅在播放模式下的单例 if (typeof(IOnlyPlayingModelSingleton).IsAssignableFrom(typeof(T))) { if (Application.isPlaying == false) { returnnull; } }
if (typeof(IAutoCreateSingleton).IsAssignableFrom(typeof(T))) { GameObject go = new GameObject($"{typeof(T).Name}"); _singleton = go.AddComponent<T>(); _singleton.OnSingletonInit(); return _singleton; }
thrownew NullReferenceException($"Singleton<{typeof(T).Name}>.Singleton -> {typeof(T).Name} is null"); } }