- Home /
GUI Button screen Width and Centering Problem
Currently I am having some trouble with my GUI button display. First i can't see the button when i play without maximizing, button don't render in the middle of the screen or in other words i can't even see it, and even if I switch to a widescreen or change the resolution, though i could see the button but its on the left hand side. Is their a solution for this...?
The code is as under:
**var customSkin:GUISkin; var buttonW:int = 100; var buttonH:int = 50; var halfScreenW:float = Screen.width/2; var halfButtonW:float = buttonW/2;
function OnGUI () {
GUI.skin = customSkin;
if(GUI.Button(Rect(halfScreenW-halfButtonW,560,buttonW,buttonH), "Play"))
{ Application.LoadLevel("game"); }**
Answer by Loius · Jun 28, 2012 at 09:18 PM
If that's all your code, halfScreenW is public, which means it doesn't change unless you change it yourself in the inspector. If you make halfScreenW a private var, I believe it will update correctly when you start the game.
Oh good spot :) Actually needs to be set in start doesn't it or be a local variable.
Answer by Mortoc · Jun 28, 2012 at 09:20 PM
I find that it's more flexible to just calculate the screen coords every frame so that when the resolution changes, weirdness doesn't ensue:
function OnGUI() {
GUI.skin = customSkin;
if( GUI.Button( Rect(
(Screen.width - buttonSize.x) * 0.5f,
(Screen.height - buttonSize.y) * 0.5f,
buttonSize.x
buttonSize.y
))
) {
Application.LoadLevel("game");
}
}
Answer by shezab · Jun 28, 2012 at 09:30 PM
Oh..... Declaring both as private vars did the trick..... but can you just a bit explain ... HOW?
Please don't use answers for comments - there's an Add New Comment button hidden on the right of the screen for that :) On Unity Answers an Answer is a Solution and not a Reply (confuses everyone the first time!)
It's because the inspector saved the width of the screen when you were running in the editor when it was public - but not when it was private.
Your answer
Follow this Question
Related Questions
Move the text in a GUI Button/Box 1 Answer
problem with gui 2 Answers
On Screen Button Controls 0 Answers