- Home /
 
How could I center a GUI box on screen?
I'm trying to make a very simple menu and want to center the GUI for it. So far I have this...
 var Menu11 : Rect = Rect(10, 10, 200, 200);
 
 function OnGUI ()
 {
     GUI.Window(0, Menu11, Menu33, "Cargo Test");
 }
 
 function Menu33(){
 if(GUILayout.Button("Play")){
 Application.LoadLevel("Cargo");
 }
 if(GUILayout.Button("Controls")){
 Application.LoadLevel("Control");
 }
 if(GUILayout.Button("Quit")){
 Application.Quit();
 }
 }
 
               ... So what would I add to make it center or change the sizes of the buttons? Any help would be appreciated.
Answer by Snawws · May 24, 2015 at 01:43 PM
The thing you have to do is to set the x and y coordinates when you create your rect to be in the center of the screen, but also relative to the window size.
Exampel Code in C#:
 private Rect Menu11;
 
     void Start () {
         int windowWidth = 200;
         int windowHeight = 200;
         int x = (Screen.width - windowWidth) / 2;
         int y = (Screen.height - windowWidth) / 2;
         Menu11 = new Rect(x,y,windowWidth,windowHeight);
     }
     
     void OnGUI () {
         GUI.Window (0, Menu11, Menu33, "Cargo Test");
     }
 
     void Menu33(int i) {
         if(GUILayout.Button("Play")){
 
         }
         if(GUILayout.Button("Controls")){
 
         }
         if(GUILayout.Button("Quit")){
 
         }
     }
 
              Answer by DanGoldstein91 · May 24, 2015 at 05:40 AM
Try tweaking the sizes a different way. Instead of using pixels...
  var Menu11 : Rect = Rect(10, 10, 200, 200);
 
               Try replacing the values with the screen width & height divided by a float. Something like this:
  var Menu11 : Rect = Rect(Screen.height/2.6f, Screen.width/7.1f, Screen.height/5.0f, Screen.width/2.7f);
 
               Screen.width and Screen.height can be used in any of those parameters. A button would be something like this:
 if(GUILayout.Button(Rect = Rect(5,Screen.height/5.2f,Screen.width/2.2f,Screen.width/7.4f), "Play"))
 
               I use C#, I'm not familiar with UnityScript but I tried my best to mimic your syntax. I may have a Syntax error in my answer
It will take a lot of tweaking to get just right. If this method is too slow and annoying, consider using Unity's current UI system instead.
Answer by Vladerx · Apr 26, 2019 at 05:55 AM
I found it when working with editor window, its better to use the active resolution instead:
 int winW = 800;
 int winH = 600;
 int winX = ( Screen.currentResolution.width - winW ) / 2;
 int winY = ( Screen.currentResolution.height - winH ) / 2;
 m_Window.position = new Rect( winX, winY, winW, winH );
 m_Window.Show();
 
              Your answer