From cb9ec76c440a687e25b88486373ab93cfa191b59 Mon Sep 17 00:00:00 2001 From: Hibnu Hishath Date: Wed, 2 Aug 2023 23:38:30 +0530 Subject: [PATCH] Adding support to look for gameobject with the don't save flag --- Scripts/Core/Singleton.cs | 27 +++++++++++++++++++++------ package.json | 2 +- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/Scripts/Core/Singleton.cs b/Scripts/Core/Singleton.cs index 62e2656..bb3d3a6 100644 --- a/Scripts/Core/Singleton.cs +++ b/Scripts/Core/Singleton.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Reflection; using UnityEngine; -using UnityEngine.SceneManagement; namespace Hibzz.Singletons { @@ -80,20 +79,33 @@ protected static T[] GetAllObjects() { #if UNITY_EDITOR - // when the editor is in play mode, FindObjectsOfType will work + // when the editor is in play mode, FindObjectsOfType will work... + // however, if the nothing was found, we can do an extensive search + // with the objects that might be marked with "Don't Save" flags if (Application.isPlaying) { - return FindObjectsOfType(); + var result = FindObjectsOfType(); + if(result.Length > 0) + { + return result; + } } // 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) + // resources api needs to be used, else it won't detect objects of + // that have a don't save flag + GameObject[] gameobjects = Resources.FindObjectsOfTypeAll(); + foreach (var go in gameobjects) { - var comps = rootObject.GetComponentsInChildren(); + // a persistent gameobject is something stored in the disk, so + // usually a prefab... ignore those type of objects + if(UnityEditor.EditorUtility.IsPersistent(go)) { continue; } + + // get all singleton objects of type T and store it in the list of singletons + var comps = go.GetComponentsInChildren(); foreach (var comp in comps) { singletons.Add(comp); @@ -105,6 +117,9 @@ protected static T[] GetAllObjects() #else + // only simple gameobject find in scene... To be honest, I don't + // see a point in instantiating objects with the Don't save flags + // in the build version of a game, so this will do fine return FindObjectsOfType(); #endif diff --git a/package.json b/package.json index ea6a0c6..1dfee82 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "com.hibzz.singletons", - "version": "1.3.0", + "version": "1.3.1", "displayName": "hibzz.singletons", "description": "A library of singletons for Unity", "author": {