Sunday, December 6, 2009

Compute Length of a String in Unity 3D

How to compute the length or size of a string in pixels wasn't immediately obvious to me in Unity 3D, which is why I thought I was quickly post how it can be done. Knowing the size of the string is often useful if you are developing your own complex controls of interfaces. It's also often commonly used for centering a string within a space.

In order to compute the size of a rendered string, you will need your string and the GUI style with which you intend to render your string, and then finally a GUI content convenience object in order to pass the string into the CalcSize method of the GUIStyle object. See below for UnityScript pseudocode.


/* declare the style and setup parameters with Unity 3D inspector */
var guiStyle : GUIStyle;

...

/* here is my string */
var myString : String = "this is my string";

/* create a content convenience object with which to pass the string */
var myContent : GUIContent = new GUIContent();
myContent.text = myString;

/* CalcSize will return the dimensions (width and height) of the rendered string in pixels */
var stringSize : Vector2 = guiStyle.CalcSize(myContent);



You can then get the x and y components on the returned Vector2 for the size of the string in pixels, width and height. Remember, the font size, font type, spacing and all the rest of the GUIStyle parameters you configured in the Unity 3D inspector will alter the final pixel size values of the string.

2 comments: