GUI in the middle of the screen

hey guys,

I am making a GUI Label appear in the middle of the screen, and this is the code that I have…:

GUI.Label(Rect(Screen.width - Screen.width/2,Screen.height - Screen.height/2,250,300), "Hello World");

Now there are no errors in the console, but when I play my game in the editor (and I made the editor window popup out and as big as possible), the GUI Label isn’t in the middle of the screen… :confused: It’s to the left and a bit down… :confused:

Would it be because it’s in the editor, or is there error in my code???



You should take the Rect width and height in account:

  var w = 250;
  var h = 300;
  private var rect = Rect((Screen.width-w)/2, (Screen.height-h)/2, w, h);
  GUI.Label(rect, "Hello World");

But if you want the Rect to be proportional to the Screen size (0=0%, 1=100%), you may use this:

  var w = 0.3; // proportional width (0..1)
  var h = 0.2; // proportional height (0..1)
  private var rect: Rect;
  rect.x = (Screen.width*(1-w))/2;
  rect.y = (Screen.height*(1-h))/2;
  rect.width = Screen.width*w;
  rect.height = Screen.height*h;
  GUI.Label(rect, "Hello World");

Despite the rect is centered, the text will still appear at the upper left rect corner. The problem here is the text alignment: it should be MiddleCenter to be centered in the rect passed to GUI.Label, but it’s UpperLeft. In order to change this, you must add a GUIStyle variable to your script, set the desired characteristics by script or in the Inspector and pass it as the last parameter of the GUI function:

  var style: GUIStyle;
  style.alignment = TextAnchor.MiddleCenter;
  GUI.Label(rect, "Hello World", style);

Another alternative is to clone the style of other GUI itens. If you use the “button” style, for instance, the rect you’ve specified will appear with the text aligned to the center:

  GUI.Label(rect, "Hello World", "button");

This style is good to see exactly how the rect appear in the screen, but since it’s the default button style, may confuse people (everybody will click it’s a button).