How can I get the full path to a GameObject?

I would like to know the full path to a GameObject in the scene. The path would contain all of the parent information for the GameObject.

For example, if I have a scene like this

-A
|-B
  |-C
|-D
-E

then the path for A would be '/A', the path for B would be '/A/B', the path for C would be '/A/B/C', etc.

Clearly we can find any object by its path, but how do I get a path from an object?

Thanks!

I couldn't see a built-in function to give you this, so here's one which you can use:

public static string GetGameObjectPath(GameObject obj)
{
    string path = "/" + obj.name;
    while (obj.transform.parent != null)
    {
        obj = obj.transform.parent.gameObject;
        path = "/" + obj.name + path;
    }
    return path;
}

That's C#. Give me a shout if you need it in JS.

Or, for those of us who love the beauty of recursion:

public static string GetPath(this Transform current) {
	if (current.parent == null)
		return "/" + current.name;
	return current.parent.GetPath() + "/" + current.name;
}

I implemented it as extension method to be able to simply write transform.GetPath();

For meaningful log messages I added the same for Component:

public static string GetPath(this Component component) {
	return component.transform.GetPath() + "/" + component.GetType().ToString();
}

which enables me to write

Debug.Log("failed to satisfy a condition in " + this.GetPath()");

Unity v5 (Editor only)

 if(this.transform!=this.transform.root)
    Debug.Log("Path:"+transform.root.name+"/"+AnimationUtility.CalculateTransformPath (this.transform,transform.root));
else  you know :)

Concise:

Debug.Log(string.Join("/", gameObject.GetComponentsInParent<Transform>().Select(t => t.name).Reverse().ToArray()), gameObject);

Remember, if you pass GameObject to Debug.Log, when you can click the log in console it will highlight it in hierarchy

Here’s my piece of code using StringBuilder and a simple array reversed for :

public static string GetFullPath(this Transform tr)
{
    var parents = tr.GetComponentsInParent<Transform>();

    var str = new StringBuilder(parents[^1].name);
    for (var i = parents.Length - 2; i >= 0; i--)
        str.Append($"/{parents*.name}");*

return str.ToString();
}