add more error-proof checking for startup singletons

This commit is contained in:
in0finite 2022-01-22 01:24:52 +01:00
parent 4556e1eed6
commit f0959761e8
2 changed files with 16 additions and 1 deletions

View file

@ -47,6 +47,8 @@ namespace SanAndreasUnity.Utilities
throw new Exception($"Awake() method called twice for singleton of type {this.GetType().Name}"); throw new Exception($"Awake() method called twice for singleton of type {this.GetType().Name}");
} }
this.OnSingletonAwakeValidate();
Singleton = (T)this; Singleton = (T)this;
this.OnSingletonAwake(); this.OnSingletonAwake();
@ -56,6 +58,10 @@ namespace SanAndreasUnity.Utilities
{ {
} }
protected virtual void OnSingletonAwakeValidate()
{
}
private void OnDisable() private void OnDisable()
{ {
if (Singleton != this) if (Singleton != this)

View file

@ -1,7 +1,16 @@
namespace SanAndreasUnity.Utilities using UnityEngine.SceneManagement;
namespace SanAndreasUnity.Utilities
{ {
public class StartupSingleton<T> : SingletonComponent<T> public class StartupSingleton<T> : SingletonComponent<T>
where T : StartupSingleton<T> where T : StartupSingleton<T>
{ {
protected override void OnSingletonAwakeValidate()
{
Scene activeScene = SceneManager.GetActiveScene();
if (!activeScene.IsValid() || activeScene.buildIndex != 0)
throw new System.Exception("Startup singleton can only be initialized in startup scene");
}
} }
} }