Hello,
I have run into a problem with making a variable number of buttons. I am working on the trade system for my project, and want to open up a new window for managing that trade. This window should display a number of buttons equal to the number of trade stops. When the buttons are clicked they are supposed to display controls for what to load and unload at that particular stop.
To that effect I have set up this script:
public class TradeGUI : MonoBehaviour
{
private Ship shipSc;
private List<SolarSystem> tradePlaces = new List<SolarSystem>();
public bool drawMe = false;
private Rect windowRect;
public void Start()
{
windowRect = new Rect(10, 10, 100, 150);
}
public void OnGUI()
{
if (drawMe)
{
windowRect = GUI.Window(0, windowRect, DrawWindow, "Trade");
}
}
private void DrawWindow(int id)
{
int i = 0;
foreach (SolarSystem sys in tradePlaces)
{
if (GUI.Button(new Rect(10, tradePlaces.Count * 30, 80, 20), sys.name))
{
PrintThis(sys.name);
}
i++;
}
}
private void PrintThis(string p)
{
print(p);
}
public void AddTradePlace(GameObject gameObject)
{
tradePlaces.Add(gameObject.GetComponent<SolarSystem>());
}
}
Of course, I wouldn’t be here if this worked. There are 2 things wrong:
-
The window will only ever display one button at a time. It appears in the right place, so with one stop it’ll position itself at (10, 30) in the window, with two stops it’ll be at (10, 60) and so on. But only ever one button, and due to the transparency of the button, you can just make out the name of the previous button ‘underneath’ the button.
Am I missing something silly here, or is there some inherent problem with making a call to GUI.Button inside a loop? -
The line to execute when the button is clicked never executes, even with just one stop. Probably a side-effect to problem 1, but I thought I should mention it all the same.
I have thought about saving each button as a var in a list (Bool btn1 = GUI.Button(new Rect(10, tradePlaces.Count * 30, 80, 20), sys.name);), and then iterating over that list in Update() to see if any of them have changed to true. Aside from being cumbersome, I can’t store the button functionality unless I use an array of arrays or some such, and then it just got more than cumbersome.
Any insights on how to generate buttons dynamically would be greatly appreciated!