- Home /
Dynamic variable creation for unique GUI.Window generation
I'm wanting each click of a button to generate a new draggable window containing text taken randomly from a string of items. What I can't figure out is how to generate completely new variables to store the necessary window data. Here is what I've got, though the way it's coded right now, each click of the New Item button will only refresh the one window:
var itemList : String[] =["Item1","Item2","Item3","Item4"];
var singleItem = "";
var wIndex = 0;
var showWindow = false;
var wRect : Rect = Rect (10,40,90,90);
function OnGUI(){
if (GUI.Button(Rect(10,10,80,20),"New Item")){
showWindow = true;
singleItem = itemList[Random.Range(0,itemList.length -1)];
wIndex++
}
if (showWindow){
wRect = GUI.Window (wIndex,wRect,newWindow,singleItem);
}
}
function newWindow(windowID:int){
GUI.DragWindow();
}
Right now it's bound to wRect to define itself and showWindow to keep it displayed. I could just make a number of similar predefined variables so high that the player would never make that many windows, but I figure there's got to be a way to do it dynamically through code.
Is it possible to somehow create a new, uniquely named variable each time the button is clicked? Something like
var "wRect"+wIndex : Rect = (10,40,90,90);
though clearly that doesn't work syntactically. I'm a little out of my depth; any help would be much appreciated.
Answer by $$anonymous$$ · Oct 10, 2013 at 01:39 AM
You can use dynamic Lists of Rects and Strings, and dynamically add items to the lists every time you click the "New Item" button.
Then, iterate over the List inside the if (showWindow) block, calling GUI.Window for each Rect and String in each list.
This should get you started, good luck!
import System.Collections.Generic;
...
var wRects : List.<Rect> = new List.<Rect>();
var wItems : List.<String> = new List.<String>();
...
function OnGUI() {
if (GUI.Button(Rect(...
...
wRects.Add(new Rect(10 * wIndex, 40, 90, 90);
wItems.Add(singleItem);
}
if (showWindow) {
for (int i = 0; i < wIndex; i++) {
GUI.Window(i, wRects[i], newWindow, wItems[i]);
}
}
}
...
Hey, thanks! It's been a while, but this is a project I'm actually going to return to shortly. Again, I'll play around with what you've provided and do some reading. $$anonymous$$uch appreciated.
Your answer
![](https://koobas.hobune.stream/wayback/20220613101040im_/https://answers.unity.com/themes/thub/images/avi.jpg)