Why do only some buttons respond to clicks?

Hello, I’m diving into Unity and I’m trying to dynamically build a GUI based on game data, but only some of the buttons respond to clicks. Below is my code. The buttons being generated in the loop are the buttons that don’t respond to my clicks, but all the buttons that are created outside of the loops do respond to click events. What gives?

void OnGUI () {
// Make a background box
GUI.Box(new Rect(10,10,800,600), “Multiplayer Games”);

	// Make the first button. If it is pressed, Application.Loadlevel (1) will be executed
	if (GUI.Button (new Rect (20,40,100,20), "Join Game")) {

	// Make the second button.
	if (GUI.Button (new Rect (130,40,100,20), "Refresh List")) {
	// Make the second button.
	if (GUI.Button (new Rect (700,40,100,20), "Create Game")) {
	string textAreaString = GUI.TextArea(new Rect (20,70,780,520), "						Server Name							Player Count								IP Address								Port");

	// Make the buttons for the game servers
	for (int i=0; i< _gameServerList.Count; i++) 
			Hashtable table = ((Hashtable) _gameServerList*);*
  •   		string serverName = (string)table["name"];*
  •   		double port = (double)table["port"];*
  •   		double id = (double)table["id"];*
  •   		string ipaddress = (string)table["ip_address"];*
  •   		double playerCount = (double)table["player_count"];*
  •   		string buttonLabelText = string.Format("{0}										{1}										{2}										{3}", serverName, playerCount, ipaddress, port);*

_ if (GUI.Button (new Rect (21,i*40+91,778,40), buttonLabelText)) //<----_

  •   		{*
  •   			Client.serverIP = ipaddress;*
  •   			Client.serverPort = (int)port;*
  •   			Application.LoadLevel("Client");*
  •   		}*
  •   }*
  • }*
    Thanks is advance for all your wisdom!

The problem is your TextField collects all input because it overlaps with your buttons.

That’s a general problem with the GUI system. Don’t overlap interactive GUI controls! Due to the immediate mode the controls are drawn in the order you call the functions therefore the last one that is drawn lays on top. But the input is processed in the same order. The first function that is called will grab the input. So always the bottom most control.

One way would be to disable the TextField so it doesn’t react to user input:

GUI.enabled = false;
GUI.TextArea(new Rect (20,70,780,520), "	......");
GUI.enabled = true;

But i would suggest to use a label or a box instead. You should be able to use the same style if you want.

GUI.Label(new Rect(...),"		...","textfield");

I’m not sure if the style names are lowercase or not, you have to try it :wink:

A label is a pure passive element so it doesn’t “eat” the input. TextFields are meant to display text that can be edited by the user.