make Find better (cache more)

This commit is contained in:
JohnCorby 2022-07-09 16:13:32 -07:00
parent c05071b746
commit 096ac539a1

View File

@ -88,13 +88,18 @@ namespace NewHorizons.Utility
public static GameObject FindChild(this GameObject g, string childPath) => public static GameObject FindChild(this GameObject g, string childPath) =>
g.transform.Find(childPath)?.gameObject; g.transform.Find(childPath)?.gameObject;
/// <summary>
/// finds active or inactive object by path,
/// or recursively finds an active object by name
/// </summary>
public static GameObject Find(string path, bool warn = true) public static GameObject Find(string path, bool warn = true)
{ {
if (CachedGameObjects.TryGetValue(path, out var go)) return go; if (CachedGameObjects.TryGetValue(path, out var go)) return go;
go = GameObject.Find(path); go = GameObject.Find(path);
if (go != null) return go; if (go == null)
{
// find inactive use root + transform.find
var names = path.Split('/'); var names = path.Split('/');
var rootName = names[0]; var rootName = names[0];
var root = SceneManager.GetActiveScene().GetRootGameObjects().FirstOrDefault(x => x.name == rootName); var root = SceneManager.GetActiveScene().GetRootGameObjects().FirstOrDefault(x => x.name == rootName);
@ -108,9 +113,9 @@ namespace NewHorizons.Utility
go = root.FindChild(childPath); go = root.FindChild(childPath);
if (go == null) if (go == null)
{ {
var name = names.Last(); if (warn) Logger.LogWarning($"Couldn't find child object in path ({path})");
if (warn) Logger.LogWarning($"Couldn't find object in path ({path}), will look for potential matches for name {name}"); return null;
go = FindObjectOfTypeAndName<GameObject>(name); }
} }
CachedGameObjects.Add(path, go); CachedGameObjects.Add(path, go);