Generic Debug Message

So, this has been bugging me for awhile now and altough this isnt something crucial, it would save me sometime.

From time to time I have to create a Debug message to… well, debug. And every message I create has the same format:

Lets say I have a variable called assetPathAndName, which is a string and holds the message “Assets/”. So my Debug.Log will be like this:

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

Which will have the following output: “assetPathAndName: Assets/”. (without the quotes)

How would I create a method which would only have a generic parameter (basically the types that Debug.Log supports, int, float, Vector3, string…) and would create a string containing both the variable name and the variable value?


Actually, this did work (tested with int, string, a Custom Interface and Vector3):

public static void Check<T>( System.Func<T> expr )
    // get IL code behind the delegate
    var il = expr.Method.GetMethodBody( ).GetILAsByteArray( );
    // bytes 2-6 represent the field handle
    var fieldHandle = System.BitConverter.ToInt32( il, 2 );
    // resolve the handle
    var field = expr.Target.GetType( )
        .Module.ResolveField( fieldHandle );

    Debug.Log( "Name is: " + field.Name );
    Debug.Log( "Value is: " + expr( ) );

Got it from this 1

Thanks @Bunny83 and @Dave Carlile for point me to the right link! =)