From c19b485a420a11861e1d0899ef494692c5e1c29b Mon Sep 17 00:00:00 2001 From: in0finite Date: Fri, 21 Jan 2022 01:14:03 +0100 Subject: [PATCH] make StartupSingleton work in edit mode --- Assets/Scripts/Utilities/F.cs | 12 ++++++ Assets/Scripts/Utilities/StartupSingleton.cs | 44 ++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/Assets/Scripts/Utilities/F.cs b/Assets/Scripts/Utilities/F.cs index 10f692e8..09442d8e 100644 --- a/Assets/Scripts/Utilities/F.cs +++ b/Assets/Scripts/Utilities/F.cs @@ -1036,6 +1036,18 @@ namespace SanAndreasUnity.Utilities } } + public static bool IsAppInEditTime + { + get + { +#if !UNITY_EDITOR + return false; +#else + return !UnityEditor.EditorApplication.isPlaying && !UnityEditor.EditorApplication.isPaused; +#endif + } + } + public static bool ScreenHasHighDensity => Application.isMobilePlatform; diff --git a/Assets/Scripts/Utilities/StartupSingleton.cs b/Assets/Scripts/Utilities/StartupSingleton.cs index af82aa2c..d57d2af8 100644 --- a/Assets/Scripts/Utilities/StartupSingleton.cs +++ b/Assets/Scripts/Utilities/StartupSingleton.cs @@ -6,7 +6,39 @@ namespace SanAndreasUnity.Utilities public class StartupSingleton : MonoBehaviour where T : StartupSingleton { +#if !UNITY_EDITOR public static T Singleton { get; private set; } +#else + private static T s_cachedSingleton; + public static T Singleton + { + get + { + if (!F.IsAppInEditTime) + { + return s_cachedSingleton; + } + + if (s_cachedSingleton != null) + return s_cachedSingleton; + + T[] objects = FindObjectsOfType(); + + if (objects.Length == 0) + return null; + + if (objects.Length > 1) + throw new Exception($"Found multiple singleton objects of type {typeof(T).Name}. Make sure there is only 1 singleton object created per type."); + + s_cachedSingleton = objects[0]; + return s_cachedSingleton; + } + private set + { + s_cachedSingleton = value; + } + } +#endif private void Awake() { @@ -24,6 +56,18 @@ namespace SanAndreasUnity.Utilities { } + private void OnDisable() + { + if (Singleton != this) + return; + + this.OnSingletonDisable(); + } + + protected virtual void OnSingletonDisable() + { + } + private void Start() { if (this != Singleton)