Unity - Extensions
2019-06-29 / 1 min read
Extensions
1. Get Hierarchy Path of a GameObject in Scene
public static string GetHierarchyPath(this GameObject obj)
{
string path = "/" + obj.name;
while (obj.transform.parent != null)
{
obj = obj.transform.parent.gameObject;
path = "/" + obj.name + path;
}
<!-- more -->
return path.Substring(1);
}
public static string GetHierarchyPath(this Transform obj)
{
string path = "/" + obj.name;
while (obj.transform.parent != null)
{
obj = obj.parent;
path = "/" + obj.name + path;
}
return path;
}
2. Get a GameObject reference from a hierarchy Path in Scene
public static Transform FindByHierarchyPath(this string path)
{
if (string.IsNullOrEmpty(path))
{
return null;
}
string[] names = path.Split('/');
var roots = SceneManager.GetActiveScene().GetRootGameObjects();
Transform parent = null;
for (int i = 0; i < roots.Length; i++)
{
if (roots[i].name == names[0])
{
parent = roots[i].transform;
break;
}
}
int index = 1;
while (parent != null && index < names.Length)
{
var child = parent.Find(names[index]);
parent = child;
index++;
}
return parent;
}