Cache root objects

This commit is contained in:
Nick 2023-08-24 12:45:25 -04:00
parent 3e23e433f7
commit eef5323869

View File

@ -10,11 +10,13 @@ namespace NewHorizons.Utility
public static class SearchUtilities public static class SearchUtilities
{ {
private static readonly Dictionary<string, GameObject> CachedGameObjects = new Dictionary<string, GameObject>(); private static readonly Dictionary<string, GameObject> CachedGameObjects = new Dictionary<string, GameObject>();
private static readonly Dictionary<string, GameObject> CachedRootGameObjects = new Dictionary<string, GameObject>();
public static void ClearCache() public static void ClearCache()
{ {
NHLogger.LogVerbose("Clearing search cache"); NHLogger.LogVerbose("Clearing search cache");
CachedGameObjects.Clear(); CachedGameObjects.Clear();
CachedRootGameObjects.Clear();
} }
public static List<T> FindObjectsOfTypeAndName<T>(string name) where T : Object public static List<T> FindObjectsOfTypeAndName<T>(string name) where T : Object
@ -107,8 +109,16 @@ namespace NewHorizons.Utility
// 2: find inactive using root + transform.find // 2: find inactive using root + transform.find
var names = path.Split('/'); var names = path.Split('/');
// Cache the root objects so we don't loop through all of them each time
var rootName = names[0]; var rootName = names[0];
var root = SceneManager.GetActiveScene().GetRootGameObjects().FirstOrDefault(x => x.name == rootName); if (!CachedRootGameObjects.TryGetValue(rootName, out var root))
{
root = SceneManager.GetActiveScene().GetRootGameObjects().FirstOrDefault(x => x.name == rootName);
if (root != null)
{
CachedRootGameObjects.Add(rootName, root);
}
}
var childPath = string.Join("/", names.Skip(1)); var childPath = string.Join("/", names.Skip(1));
go = root ? root.FindChild(childPath) : null; go = root ? root.FindChild(childPath) : null;