Posts Tagged guilayout

Fixing the width of strings displayed in the Unity GUI


Firstly, I know what you are going to say – you should just use two aligned labels, rather than fiddling around with string formatting – but sometimes that just doesn’t work – like when you want the items in a popup to have columns like here:

No chance for using labels in that component.  So there is a way of effectively padding text to a given width.  You basically work out the width of a ” “, a tab and the string, then use that combination to make a new string which is the correct width.

Just using string.PadRight(20) doesn’t work due to the variable width of characters in the font.


public static class TextHelper
{
	public static string FixTo(this string str, float width, string type="label")
	{
	    var widthOfTab = GUI.skin.GetStyle(type).CalcSize(new GUIContent("\t")).x;
		var widthOfSpace = GUI.skin.GetStyle(type).CalcSize(new GUIContent(" ")).x;
		var widthOfString = GUI.skin.GetStyle(type).CalcSize(new GUIContent(str)).x;
	    return str + new String(' ', (int)((width-widthOfTab)/widthOfSpace)+1) + "\t";
	}
}

You basically use myString.FixTo(150) to fix it based on the width of a “label” in the skin or you can override it to set a different font by using myString.FixTo(200, “box”).

Should work fine in javascript so long as you make a .cs file out of this and put it in your plugins folder.

, , , ,

1 Comment