diff --git a/Scripts/Core/Singleton.cs b/Scripts/Core/Singleton.cs index 08a0d58..62e2656 100644 --- a/Scripts/Core/Singleton.cs +++ b/Scripts/Core/Singleton.cs @@ -36,7 +36,7 @@ public static T Instance // Used to create a new instance of the singleton private static T RequestNewInstance() { - T[] items = FindObjectsOfType(); + T[] items = GetAllObjects(); if (items.Length == 0) { // Using the reflection system, look if CreateNewInstance is being overriden @@ -71,6 +71,45 @@ protected static T CreateNewInstance() return obj.AddComponent(); } + // Summary: Get all components of type T in the scene + // Remarks: This is an editor friendly version of FindObjectsOfType + // that works on singletons that exist on an editor context. + // The function is more expensive in editor context, however + // remains cheap in regular playmode. + protected static T[] GetAllObjects() + { + #if UNITY_EDITOR + + // when the editor is in play mode, FindObjectsOfType will work + if (Application.isPlaying) + { + return FindObjectsOfType(); + } + + // the editor is not in playmode, so in the editor context + // this container will store all objects found of type T in the scene + List singletons = new List(); + + GameObject[] rootObjects = SceneManager.GetActiveScene().GetRootGameObjects(); + foreach (var rootObject in rootObjects) + { + var comps = rootObject.GetComponentsInChildren(); + foreach (var comp in comps) + { + singletons.Add(comp); + } + } + + // convert the list to an array, as that's the return type expected + return singletons.ToArray(); + + #else + + return FindObjectsOfType(); + + #endif + } + // when the singleton object gets destroyed, we make sure that the // static singleton reference is cleared protected virtual void OnDestroy() diff --git a/package.json b/package.json index fca826f..ea6a0c6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "com.hibzz.singletons", - "version": "1.2.0", + "version": "1.3.0", "displayName": "hibzz.singletons", "description": "A library of singletons for Unity", "author": {