How Do I Center A GUI Label?

Hi, I'm using the following:

GUI.Label (Rect (0,0,100,50), "BLAH");

What would I set it to for it to be centered on the screen instead of the left corner?

You need a GUIStyle that has a centered alignment. You can do this programmatically by getting an existing style and setting the alignment:

function OnGUI () {
    var centeredStyle ="Label");
    centeredStyle.alignment = TextAnchor.UpperCenter;
    GUI.Label (Rect (Screen.width/2-50, Screen.height/2-25, 100, 50), "BLAH", centeredStyle);

Or you can make your own style, set it up in the inspector to include centering, and use that:

var myStyle : GUIStyle;

function OnGUI () {
    GUI.Label (Rect (Screen.width/2-50, Screen.height/2-25, 100, 50), "BLAH", myStyle);

This seems to work for me in C#, should be similar in Javascript. :slight_smile:

GUI.Box (new Rect ((Screen.width)/2 -(Screen.width)/8,(Screen.height)/2-(Screen.height)/8,(Screen.width)/4,(Screen.height)/4), “Centered Box”);

hey there again! here's the code to do that:

    var windowWidth : int = 200;
    var windowHeight : int = 200;
    /*var here from your other script should be Str. doesn't have to be in this script though. that's what ScriptName.StaticVarName does. 
goes through that script to find that static var. 
only works for static vars as far as i know.

    function OnGUI()

     GUI.Window(0, Rect((Screen.width / 2) - (windowWidth / 2), 
                                   (Screen.height / 2) - (windowHeight / 2), 
                                   windowHeight), Message.Str); // should be centered. 

and if it's not centered, play around with the window height / width, and if it's still not working, let me know.

Another way is to set the alignment to “Upper Center” in the GUIStyle. Set your label to be anchored to the x=0 and height you want, then make sure your label width is set to the screen width. Eg
GUI.Label (Rect (0, Screen.height/2-25, Screen.width, 50), “BLAH”, myStyle);

This works with dynamic text.

Thanks, everyone!

I spent half a day on this,

and I realize it was because of the ** Rect** not centering,

not because of the GUI Label.

A quick fix would be to move the starting point of the Rect back by half of the of its width, then the GUI Label should be at the center.

float rectWidth = 500;
float rectHeight = 30;

GUI.Label(new Rect(Screen.width / 2 - ( rectWidth / 2 ), Screen.height / 2, rectWidth, rectHeight), "Text", centeredStyle);

centeredStyle is from the answer above by @Eric5h5