It’s a Word Wrap!

Can’t recall where we found this script – probably the Unity forums – but we want to share it on the blog, because it’s been a nifty little script to have. It’s an auto word-wrapper.

So rather than manually typing the /n’s into your long text descriptions, just dump this little script onto your GUIText object, and presto! Word wrapping. You can chose the maximum width and height of the wrap, line length and co-ords. And you never have to type /n again! This is also great if you have localisation on long text. Nothing worse than hand-formatting every – single – translation!

It’s in UnityScript, have yet to convert to C#:


var lineLength = 400;
private var words : String[];
private var wordsList : ArrayList;
private var result = "";
var TextSize: Rect;
private var numberOfLines = 1;

function FormatString ( text : String )
{
	words = text.Split(" "[0]); //Split the string into seperate words
	result = "";

	for( var index = 0; index < words.length; index++)
	{
	    var word = words[index].Trim();

	    if (index == 0)
	    {
                result = words[0];
                guiText.text = result;
	    }

    	    if (index > 0 )
    	    {
		result += " " + word;
		guiText.text = result;
	    }

    	    TextSize = guiText.GetScreenRect();

            if (TextSize.width > lineLength)
            {
        	//remover
	        result = result.Substring(0,result.Length-(word.Length));
    	        result += "\n" + word;
	        numberOfLines += 1;
    	        guiText.text = result;
            }
      }
}

(And apologies too for WordPress’ god-awful code writing tools that creates really ugly code presentation)

Leave a comment