Center GUI.Label similar to GUIText?

The only examples I could find of “centering” GUI Labels here have been the text within the labels. However, I want to physically center the text as you can do with GUITexts.

For example, I have a GUI Label that’s 200 wide with the text “Hello”. If I set the x-coor to Screen.width/2, I want to be able to have that text always centered by anchoring the text by the middle to that coordinate. You can do the same thing with a GUIText using TextAnchors, but they function differently. Labels simply center the text within their Rect.

Is there any way to physically anchor a GUI.Label?

Just take a look at GUIStyles and especially GUIStyle.alignment ( TextAnchor)

If you don’t want to create your own GUISkin, which would simplify such setups a lot since you can easily edit your skin in the inspector, You can create a temporary GUIStyle like this:

void OnGUI()
    // copy the "label" style from the current skin
    GUIStyle centeredTextStyle = new GUIStyle("label");
    centeredTextStyle.alignment = TextAnchor.MiddleCenter;
    GUI.Label(yourRect, "The text",centeredTextStyle);

If you use a GUISkin you can either change the label style (not recommended) which will influence all labels that are drawn with this skin, or add a custom style to the skin. Just name your style e.g. “centeredText” and use it like this:

public GUISkin skin; // assigned in the inspector
void OnGUI()
{ = skin;
    // Just use the style name you like.
    GUI.Label(yourRect, "The text", "centeredText"); 

Just as an additional hint: everything in the UnityGUI is drawn using styles. You can use any style to draw any content.

This will draw a label that looks like a button:

GUI.Label(rect, "MyText", "button");

This will create a button that is of course clickable but looks like a label:

if (GUI.Button(rect, "MyText", "label"))

Feel free to explore the power of the GUI system :wink:

You can multiply the number of letters in your string by a constant value which would be the pixels by letter value and then place it in Screen.widht/2 - (number of letters * constant)/2.

string myString = "hello";
textWidth = myString.Length * 10;

//10 is a constant which will obviously vary as you change the font or its size, 
//so you'll need a little of pacience to get a good value there

GUI.Label(new Rect(Screen.width/2 - textWidth/2, Screen.height/2, textWidth, 20), myString);

This is not the better way to do it but can give you some good results.
I think other way of doing it is creating a custom GUISkin and play around with the Label options. May exist some sort of option for centering the text.