Unity Extension for Logging Syntax

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();
	}	
}

Please take a moment to read this!

Did this article help you out?  I'm a tech writer and I do this in my free time. The way I make money is when attractive people like you support me by buying me a beer, or by choosing to keep your data safe with a competitively priced off-site backup solution that I personally use. You can also sign up for Robinhood and Webull and we both get free stocks. (My friend won $168 in JPMorgon stock when I invited her.) Deposit $100 and you typically get more free stock. Want more? Head over to my About Page and try out one of the many links I've listed there.

Leave a Reply

  

  

  

This site uses Akismet to reduce spam. Learn how your comment data is processed.