- Home /
Problem managing GUI:Window buttons
Hi, guys:
I'm having a problem with buttons inside a GUI Window. I want a message appears when the player clicks a button to remind him he has chosen that option, but i dont want to use option buttons, just normal ones. So i got this code:
/*EDIT:*/ string txt_menu1="";
void OnGUI (){
GUI.Window(1, new Rect(20, 20, 180, 300), menu1, "Menu One");
}
void menu1(int windowID) {
if (GUI.Button(new Rect(10, 20, 160, 50), "Choose option 1")) {
UseType1=true;
txt_menu1="You have chosen Option 1";
}
GUI.Label(new Rect(10,200,160,90), txt_menu1, "Box");
}
This is not working. When i press the button nothing happens. I'm guessing the function menu1 is only called on creation though i've seen in the documentation some examples where the code is written there, in the Window creation function, same for the text to be shown (txt_menu1). What am i doing wrong?
Are you sure you're not resetting txt_menu1
somewhere else in your code? If you copy this snippet into a new script, remove UseType1=true;
line and declare txt_menu1
string variable outside of menu1 method, it works as expected.
So you can only run 1 line of code inside the function? If i declare txt_menu1 outside of menu1 method, how will it react to click? It will be created with that text ins$$anonymous$$d of when player clicks it. Right?
You can use as many lines of code inside a function/method. I just suggested removing that line, because when you copy the snippet to a new script, UseType1
variable will not be declared there :)
And regarding txt_menu1
variable - it must be declared in a class, outside of the menu1
method, because this way it can keep its value after exiting the method.
txt_menu1 is declared in the body of that script, outside OnGUI and outside menu1 method, it belongs to the main class. You mean to change its value outside the method? But how can i tell the program to change its value when the player presses the button?
Answer by Statement · Dec 09, 2013 at 04:27 PM
Seems to work just fine here (4.3.1f1)
@ArkaneX is probably right in that you are setting the variables elsewhere.
(I also obtained a new ID from GUIUtility rather than passing it a magic number.)
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour
{
public bool UseType1;
public string txt_menu1;
void OnGUI ()
{
int id = GUIUtility.GetControlID(FocusType.Passive);
GUI.Window(id, new Rect(20, 20, 180, 300), menu1, "Menu One");
}
void menu1 (int windowID)
{
if (GUI.Button(new Rect(10, 20, 160, 50), "Choose option 1"))
{
UseType1 = true;
txt_menu1 = "You have chosen Option 1";
}
GUI.Label(new Rect(10, 200, 160, 90), txt_menu1, "Box");
}
}
Answer by Baalhug · Dec 09, 2013 at 04:59 PM
If i use GUIUtility it works. Gonna check that function because i have 2 windows (ids 1 and 2 mannually) and it's not allowing me running it twice.