Tuesday, 29 June 2021

Unity hack - logging full object path instead of just its name

When debugging some Unity-related problem, there is often need of finding which game object in the scene does something. We can use transform.name (or gameObject.name), but there are often multiple objects in the scene with such name. The better solution would be to log full path in the scene graph (in a manner : objectsGrandParent/objectsParent/theObject). 

I don't know of any built-in solution for that, here is the helper class I've created for that purpose.

It takes transform as a parameter, of course we can call it with gameObject.transform if necessary.

using UnityEngine;

public class ScenePath
{
    public static string getPath(Transform transform)
    {
        string result = "";
        while (transform != null)
        {
            result = transform.name + 
                ((result!="")?("/" + result):"");
            transform = transform.parent;
        };

        return result;
    }
}

It can be used like this:

class MyBehaviour : MonoBehaviour
{
    void Awake()
    {
        Debug.Log(ScenePath.getPath(transform));
    }
}

As a result, if we add the MyBehaviour script to MyObject object in hierarchy like this:



... and run our scene, the logs will show up:




No comments:

Post a Comment

Python crash course part 10: inheritance and polymorphism

In the last part we've shown how to create and use a class in Python. Today we're going to talk about inheritance: wchich means cre...