- Home /
How do I center things on screen using GUILayout?
I have a GUILayout button. How would I center it on screen?
void OnGUI()
{
GUILayout.Button("OK");
}
Answer by Lance Sun · Dec 07, 2009 at 11:04 AM
K, I figured out one way to do it. It's not the most compact code, but it's not too bad.
void OnGUI() { GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height)); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace();
GUILayout.Button("OK");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.FlexibleSpace();
GUILayout.EndArea();
}
Answer by duck · Dec 07, 2009 at 11:05 AM
You need to enclose it inside a BeginArea and EndArea block, like this:
function OnGUI () {
GUILayout.BeginArea (Rect((Screen.width/2)-50, (Screen.height/2) , 100, 100));
GUILayout.Button ("OK");
GUILayout.EndArea ();
}
For more information, read about GUI Layout Modes in the manual.
Thanks. I saw that, but I don't want to override the automatic sizing. Also, it doesn't perfectly center it vertically.
To use this approach (should anyone want to override the automatic sizing), you'd use the following Rect in place of the one above "Rect((Screen.width / 2) - (buttonWidth / 2), (Screen.height / 2) - (buttonHeight / 2), buttonWidth, buttonHeight)" where button width and height are, obviously, variables containing the desired width and height of the button.
Answer by loboho · Mar 16, 2016 at 05:43 PM
Here's my solution:
GUIContent btnTxt = new GUIContent("OK");
var rt = GUILayoutUtility.GetRect (btnTxt, GUI.skin.button, GUILayout.ExpandWidth(false));
rt.center = new Vector2(EditorGUIUtility.currentViewWidth / 2, rt.center.y);
GUI.Button(rt, btnTxt, GUI.skin.button)
Answer by FurySven · Sep 06, 2019 at 09:15 AM
If you want to center button in the current line, my solution is:
void OnGUI () {
GUILayout.BeginHorizontal();
int iButtonWidth = 100;
GUILayout.Space(Screen.width/2 - iButtonWidth /2);
if (GUILayout.Button("YOUR BUTTON", GUILayout.Width(iButtonWidth ), GUILayout.Height(80)))
{
//you code here
}
GUILayout.EndHorizontal();
}