From f0959761e8d3a293197d26b36700643d6490d228 Mon Sep 17 00:00:00 2001 From: in0finite Date: Sat, 22 Jan 2022 01:24:52 +0100 Subject: [PATCH] add more error-proof checking for startup singletons --- Assets/Scripts/Utilities/SingletonComponent.cs | 6 ++++++ Assets/Scripts/Utilities/StartupSingleton.cs | 11 ++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/Assets/Scripts/Utilities/SingletonComponent.cs b/Assets/Scripts/Utilities/SingletonComponent.cs index 1153c8aa..ace8b06c 100644 --- a/Assets/Scripts/Utilities/SingletonComponent.cs +++ b/Assets/Scripts/Utilities/SingletonComponent.cs @@ -47,6 +47,8 @@ namespace SanAndreasUnity.Utilities throw new Exception($"Awake() method called twice for singleton of type {this.GetType().Name}"); } + this.OnSingletonAwakeValidate(); + Singleton = (T)this; this.OnSingletonAwake(); @@ -56,6 +58,10 @@ namespace SanAndreasUnity.Utilities { } + protected virtual void OnSingletonAwakeValidate() + { + } + private void OnDisable() { if (Singleton != this) diff --git a/Assets/Scripts/Utilities/StartupSingleton.cs b/Assets/Scripts/Utilities/StartupSingleton.cs index 0bd55780..f8369f4c 100644 --- a/Assets/Scripts/Utilities/StartupSingleton.cs +++ b/Assets/Scripts/Utilities/StartupSingleton.cs @@ -1,7 +1,16 @@ -namespace SanAndreasUnity.Utilities +using UnityEngine.SceneManagement; + +namespace SanAndreasUnity.Utilities { public class StartupSingleton : SingletonComponent where T : StartupSingleton { + 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"); + } } }