Text string width

I’m trying to display a GUI.Box which contains some dynamic text. I need this box to be just wide enough to fit the text. In other words, I need it to automatically size to fit the dynamic text. Is there a good way of doing this? I imagine I would need some way to measure the width of the text string that the GUI.Box will contain, how do I do that?

I would say you should just play with it until it is a little longer than the max amount of text you can enter. Remember, some characters are wider than others!

In my scenario the length of the text can vary quite a bit, having one huge fit-all box would result in many cases where there is a big waste of space.

To put context on things… I’m using this box to display a tooltip right on top of an object the mouse is hovering over, much like the tooltip you see when you however over a titled image in Safari. Some objects have long descriptions, some short.

The more or less obvious brute force approach to this problem is to create a lookup table by hand from the font texture which contains widths for all characters. The lookup table can then be used to calculate the width of any string in that font. I rather not do this because I would have to recompute the table if I ever change my font!

Can anyone think of a better solution?

Have you looked into GUI.Window? It can auto-scale to fit your content if you’re using GUILayout to create it.

First, We have a new fantastic forum for UnityGUI stuff, so please use that :slight_smile:

As for your actual problem? Why not use GUILayout instead of GUI? This code will display a box of the right size:

function OnGUI () {
    GUILayout.Box ("This is a string. I've no idea how long it actually is");
}

If you want to get the size of a string, look into GUIStyle.CalcSize. Something like:

var size = GUI.skin.GetStyle ("Box").CalcSize (GUIContent ("Hello World"));

Perfect, thank you!

I didn’t know we had a new GUI forum, I’ll direct my related posts there from now on!

For those who really need it I’ve written a string padding class that takes account of variable width fonts in Unity, you can get it here