- Home /
GUI button off centre
Hi, I'm brand new to scripting, I've been trying to do tutorials but kept coming across things that weren't working and I am not learning anything that way so decided to just learn from scratch and use the scripting reference. That being said I am just trying to start out small and build a GUI menu. The problem am I am having is I can't seem to get the button in the centre of my screen no matter what I have tried.
The button is in the middle of my screen when the game window in minimized but soon as I maximize it it's no longer in the middle of my screen. I am going to provide screen shots and the code of what I have. well just off centre.
using UnityEngine;
using System.Collections;
public class MyGui : MonoBehaviour
{
public float screenH = Screen.height*.5f;
public float screenW = Screen.width*.5f;
public float buttonW = Screen.width * .1f;
public float buttonH = Screen.height * .1f;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void OnGUI ()
{
//Make menu box
// GUI.Box (new Rect (10,10, 150, 250),"Main Menu");
{
//This is a button
if (GUI.Button (new Rect (screenW, screenH, buttonW, buttonH), "Button"))
{
Debug.Log ("You clicked Me!");
}
}
}
}
Any help or advice would be greatly appreciated.
I am not going to post this as an answer, as I do not know if it will work, but try turning the aspect ratio to 16:9 by clicking where it says "Free Aspect" and turn it to 16:9.
Answer by KellyThomas · Dec 22, 2013 at 04:57 PM
You initialize some of your variables in the class declaration:
public float screenH = Screen.height*.5f;
public float screenW = Screen.width*.5f;
public float buttonW = Screen.width * .1f;
public float buttonH = Screen.height * .1f;
These will be run "early" in the application lifecycle, possibly before Screen is fully initialized.
Try assigning the values during the start method:
public class MyGui : MonoBehaviour
{
public float screenH;
public float screenW;
public float buttonW;
public float buttonH;
// Use this for initialization
void Start ()
{
screenH = Screen.height * 0.5f;
screenW = Screen.width * 0.5f;
buttonW = Screen.width * 0.1f;
buttonH = Screen.height * 0.1f;
}
// ... the rest of your class ...
You were pretty close actually, they had to be declared inside the OnGUI method.