- Home /
GUI.Box doesn't show when GUI.Button is clicked
Hey! This is kind of a beginner's question, but I can't seem to make this work and I'm getting kind of frustrated. I have a tools box which contains two buttons, and I'd like that each time the player clicks one of those buttons, a GUI.Box will be drawn in the screen with some info.
This is the code I have:
// C#
private void OnGUI() {
...
if (GUI.Button(addGroupRect, "+Group")) {
Debug.Log("+Group");
GUI.Box(new Rect(20, topPanHeight + 20, 100, 30), "Box1");
}
if (GUI.Button(addElemRect, "+Elem")) {
Debug.Log("+Elem");
GUI.Button(new Rect(40, topPanHeight + 20, 100, 30), "Elem");
}
Any ideas on why nothing new is drawn when the buttons are clicked?
Thanks in advance,
Valter
Answer by Demigiant · Oct 17, 2012 at 01:31 PM
With your code, the GUI.Box is drawn only the instant (if...) the button is pressed. You should set a boolean variable that tells if the box needs to be drawn or not, and change that when a button is pressed.
I had tried before with the boolean variable, but it didn't work either.
Here's my code using the boolean:
bool show = false;
if (GUI.Button(addGroupRect, "+Group")) {
show = true;
}
if (show) {
GUI.Box(new Rect(20, topPanHeight + 20, 100, 30), "Box1");
Debug.Log("+Box1");
}
The more strange is that the string "+Box1" is printed in the console when the Button is clicked, but the Box is not drawn on the screen.
Since the number of boxes that will have to be displayed are not known before runtime, I'm not sure if using one boolean would work with multiple instances of Box and Button.
"bool show = false" should be declared outside of the OnGUI method. Otherwise you're resetting it to false each time OnGUI is called (many times x frame), and thus it will be still be true only the instant the button is pressed. If you need more than one box, than you'll need a List, but the logic stays the same.
Oh yes, of course, I forgot that. Thank you! Now it works with the bool variable code. Don't know why it doesn't with my previous one, though, but as long as it works, fine to me!
Thanks.
Answer by m4s4m0r1 · Oct 17, 2012 at 01:29 PM
maybe you can adjust you GUI Depth. for more information, you can see in this site
http://docs.unity3d.com/Documentation/ScriptReference/GUI-depth.html
maybe it can help you...