I have grown tired of writing the line of code required to log a variable to the Unity console. It gets old. In C# there is a concept by the name of “Extensions” that lets you extend classes that are locked and cannot be inherited from. Using extensions I was able to improve the syntax of debug code for most applications.
// Typing this gets old. Debug.Log(variableName);
What if you could type this instead?:
// This offers advantages because you don't // have to write the variable within parenthesis. // Why is this important? Because logging is almost // always an afterthought because you are looking for // a bug. Being able to append to the end of a line // of code is far more pleasing than wrapping an // existing line of code into another. variableName.DebugLog();
What if the function still returned the object so it can be used in code?:
// Captures the player's position in 3D space and
// logs it at the same time!!
Vector3 playerPosition = GameObject.FindObjectWithTag("Player").transform.position.DebugLog();
// Log output: (4.3, 2.0, 0.0)Source Code
// ObjectExtension.cs
using UnityEngine;
using System.Collections;
public static class ObjectExtension {
public static T DebugLog(this T o)
{
Debug.Log(o);
return o;
}
}Example Usage
Please note that ToVector3() is another extension example, used to convert Vector2 to Vector3. (Just to give you more wild ideas.)
// TestExtension.cs
using UnityEngine;
using System.Collections;
public class TestExtension: MonoBehaviour {
void OnGUI()
{
GameObject.FindGameObjectWithTag("Player").transform.position.DebugLog();
Vector3 mp = Event.current.mousePosition.ToVector3();
Ray ray = Camera.current.ScreenPointToRay(mp).DebugLog();
}
}