x


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");
}
more ▼

asked Dec 07, 2009 at 10:24 AM

Lance Sun gravatar image

Lance Sun
1.2k 26 25 52

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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();
}
more ▼

answered Dec 07, 2009 at 11:04 AM

Lance Sun gravatar image

Lance Sun
1.2k 26 25 52

(comments are locked)
10|3000 characters needed characters left

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.

more ▼

answered Dec 07, 2009 at 11:05 AM

duck gravatar image

duck ♦♦
47.5k 129 189 457

Thanks. I saw that, but I don't want to override the automatic sizing. Also, it doesn't perfectly center it vertically.

Dec 07, 2009 at 11:06 AM Lance Sun

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.

Dec 07, 2009 at 02:01 PM burnumd
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5735
x229

asked: Dec 07, 2009 at 10:24 AM

Seen: 13650 times

Last Updated: Dec 07, 2009 at 10:24 AM