Extending Debug.Log to display the name of the variable automatically

I frequently want to know what’s the name of variable and its value:

Debug.Log("variableName: " + variableName);

This might output “variableName: true”

I would like to only have to write something like this instead, as it is faster and if the name of the variable changes it will still display the correct name so I won’t have to change this debug line:

DebugExt.Log(variableName);

The output would be the same “variableName: true”

How can I achieve this? I think it’s related to reflection but I don’t know the subject too well.

It would be really tricky to figure out a generic function to do that, because the instant the variable goes into that function, it has a different name. If it’s a data type (int, float, string, Vector3) it’ll actually be copied and won’t even refer to the same object, while if it’s a reference type (most objects), it could have multiple references in memory pointing to it, and almost certainly won’t know which one you’ve passed into it, if it even has access to the one you’ve passed into it at all.

You can simplify the syntax slightly with string interpolation like this:

Debug.Log($"variableName: {variableName});

And you could write a Visual Studio extension to output that more easily, but I don’t think anything shorter than that would be possible.

2 Likes

If you want to log the name and current value of a member variable, it can be done using reflection and extension methods. Here’s the implementation:

using System.Reflection;
using JetBrains.Annotations;
using UnityEngine;

public static class LogValueExtension
{
    public static void LogValue([NotNull]this object fieldOwner, string fieldName)
    {
        var field = fieldOwner.GetType().GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        var fieldValue = field.GetValue(fieldOwner);

        Debug.Log(fieldName + ": "+(fieldValue == null ? "null" : fieldValue.ToString()));
    }
}

And here’s how you would use it:

using UnityEngine;

public class LogValueTest : MonoBehaviour
{
    public int value = 0;

    public void OnEnable()
    {
        this.LogValue(nameof(value));
        value++;
        this.LogValue(nameof(value));
        value++;
        this.LogValue(nameof(value));
    }
}

This simple implementation only supports fields, but it could easily be expanded to also support properties.

1 Like

You can have a look at my answer in stackoverflow: