Positioning GUI.Label behind guiText

Hi, I've nearly finished a game that uses quite a lot of guiText and I've suddenly realised some of the text is a bit unclear because of what's behind it. I know I can change the text colour, but because the background is constantly changing there isn't a suitable single color.

What I weant to do is to put a white oblong behind black text so that it always shows up, and I've been looking at GUI.Label and I'm using the following code:

function OnGUI(){
GUI.Label (Rect (50,90, textureToDisplay.width, textureToDisplay.height), textureToDisplay);
}

My problem concerns the width and position of the label. My text is constantly changing and is different lengths, so it's sometimes a single word on one line and sometimes several sentences over several rows, whilst (if I've understood correctly) the label always remains the same size as the texture.

At the moment, in order to accommodate the longer lines of text, I'm using a large texture. But when, a few seconds later, the text changes to one or two words on a single line, the large label is obviously too large.

I'm assuming I can write code to change the texture I'm using, but I'm using text so often that it would take a while to go back through all the game to do so.

Before I do things the hard way ... is there an easy way of matching the size of label to the size of text displayed?

What I don't want, is to do things the difficult way, then to find there's an easy way!

What you ask is more complicated than you need. Use GUIElements (guiTexture, guiText) or UnityGUI (GUI.Label, etc.) but don't mix the two.

Method A. You can put a GuiTexture behind the GuiText. You set the size of the texture to the rectangle of the guiText, which you get by calling GetScreenRect.

Try the following:

1) Add a guiTexture to the same GameObject that has the GuiText on it. Make sure the transform's scale is 0, 0, 0. Set the texture to the background you want.

2) Add the following code to a script under this GameObject. I put it in Update but you only need to run it when the text changes:

var r = guiText.GetScreenRect();
guiTexture.pixelInset.width = r.width;
guiTexture.pixelInset.height = r.height;
guiTexture.pixelInset.y = -r.height;

Method B. Instead of using a GUI.Label as the background, you can use the GUI.Label to draw both the text and it's background. By setting the GUIStyle of the label you can control the font, foreground color, background texture, put a border around it, and other things.