avatar

Unity3D: Printing Vector3

mic_vector3 Everyone who coded for Unity3D has come across this problem; Print a Vector3 and get this:

Code   
(1.2, 0.0, 2.0)
That’s not very useful, especially since the X-part is actually 1.23.

With the help of an extension-class we can fix this by adding a function to the Vector3 struct:

Code   
using UnityEngine;
 
public static class Vector3Extension
{
	public static void print(this Vector3 _vector)
	{
		Debug.Log("(" + _vector.x.ToString("0.0#######") + ", " + _vector.y.ToString("0.0#######") + ", " + _vector.z.ToString("0.0#######") + ")");
	}
}
Now, when you want to print a Vector3, you can just do this:
Code   
aVector.print();
And get this more precise version of the vector from before:
Code   
(1.23, 0.0, 1.987387)
Rather more useful really. And you can just copy&paste the class to any of your projects. For my uses I added more overload functions that add a string and a Transform to additionally pass to the Debug.Log() for even more detailed messages.

This entry was posted in Code, Devblog and tagged , , . Bookmark the permalink.