Improved search functions

This commit is contained in:
Nick J. Connors 2022-02-04 01:23:51 -05:00
parent 1a48f701c9
commit c322fe15f6
2 changed files with 74 additions and 7 deletions

View File

@ -29,13 +29,7 @@ namespace NewHorizons.Utility
public static void LogPath(GameObject go) public static void LogPath(GameObject go)
{ {
if (go == null) Log("Can't print path: GameObject is null"); if (go == null) Log("Can't print path: GameObject is null");
else Log($"{GetPath(go.transform)}"); else Log($"{SearchUtilities.GetPath(go.transform)}");
}
private static string GetPath(Transform current)
{
if (current.parent == null) return "/" + current.name;
return GetPath(current.parent) + "/" + current.name;
} }
public static void Log(string text, LogType type) public static void Log(string text, LogType type)

View File

@ -72,5 +72,78 @@ namespace NewHorizons.Utility
return null; return null;
} }
public static string GetPath(Transform current)
{
if (current.parent == null) return "/" + current.name;
return GetPath(current.parent) + "/" + current.name;
}
/*
public static GameObject Find(string path)
{
var go = GameObject.Find(path);
if (go != null) return go;
var names = path.Split(new char[] { '\\', '/' });
foreach (var possibleMatch in FindObjectsOfTypeAndName<GameObject>(names.Last()))
{
Logger.LogPath(possibleMatch);
if (GetPath(possibleMatch.transform) == path) return possibleMatch;
}
return null;
}
*/
public static GameObject Find(string path)
{
var go = GameObject.Find(path);
if(go == null)
{
var names = path.Split(new char[] { '\\', '/' });
// Get the root object and hope its the right one
var root = GameObject.Find(names[0]);
if (root == null) root = FindObjectOfTypeAndName<GameObject>(names[0]);
var t = root?.transform;
if (t == null)
{
Logger.LogWarning($"Couldn't find root object in path ({names[0]})");
return null;
}
for (int i = 1; i < names.Length; i++)
{
var child = t.transform.Find(names[i]);
if(child == null)
{
foreach(Transform c in t.GetComponentsInChildren<Transform>(true))
{
if(t.name.Equals(names[i]))
{
child = c;
break;
}
}
}
if (child == null)
{
Logger.LogWarning($"Couldn't find object in path ({names[i]})");
return null;
}
t = child;
}
go = t.gameObject;
}
return go;
}
} }
} }