- Home /
How to initialize a boolean only once when used in a function when called OnGUI
I've been building a dropdown function to place online for others trying to make something similar. I want to be able to use this same function in multiple instances throughout a GUI. I couldn't find a way to return more than one variable and this will later be return the choice of the menu. Here's what I have so far:
var show : boolean = false;
function List(headbox : Rect, dropheight : float, listheader : String, list : String[])
{
//reference # for list element
var selection : int = 0;
//fullbox starts at the bottom of the headbox
var fullbox : Rect = Rect(headbox.xMin, headbox.yMax, headbox.width, dropheight);
if(GUI.Button(headbox, listheader + ": " + list[selection]))
{
if(show != true)
show = true;
else
show = false;
}
if(show)
{
GUI.Box(fullbox, " ");
for(var l : int = 0; l < list.length; l++)
{
var entryystartpoint : float = fullbox.yMin + (l * (fullbox.height/list.length));
var entryheight : float = (fullbox.height/list.length);
if(GUI.Button(Rect(fullbox.xMin, entryystartpoint,fullbox.width, entryheight), list[l]))
{
selection = l;
show = false;
}
}
}
}
Sample calling:
var lister : String[] = new String[4];
lister[0] = "element 1";
lister[1] = "element 2";
lister[2] = "element 3";
lister[3] = "element 4";
function OnGUI()
{
List(Rect(50, 150, 150, 50), 150, "Choose one", lister);
}
I've seen several attempts online and the unify javascript example doesn't work so is there a way to send multiple variables back or pass by reference the Boolean? Thanks!
Answer by dandago · Jun 05, 2013 at 10:52 PM
One way (not quite popular) is to use an out parameter. You can then return the boolean via the out parameter.
Another way is to put your current return value and the boolean into a class, and return that.
It's up to you to choose which is best for your scenario.
I know you can return a class and organize it that way. Can you give me an example of setting up a basic class and returning it. I've tried before but haven't been able to get it to work in javascript or unity for that matter. (I haven't used javascript outside of Unity) Thank you
@pborg Just look it up, there are plenty of tutorials out there for creating classes