I have a GUILayout button. How would I center it on screen?
void OnGUI()
{
GUILayout.Button("OK");
}
I have a GUILayout button. How would I center it on screen?
void OnGUI()
{
GUILayout.Button("OK");
}
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();
}
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)
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();
}
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.
– Lance_SunTo 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.
– burnumd