Search Unity

using foreach and generating buttons

Discussion in 'UGUI & TextMesh Pro' started by ManAmazin, Aug 31, 2014.

  1. ManAmazin

    ManAmazin

    Joined:
    Aug 7, 2013
    Posts:
    246
    if there any difference how i would translate this with the new UI?


    GUILayout.BeginArea(new Rect(Screen.width - 350, 0, 350, Screen.height), "Available Games", "Box");
    GUILayout.Space(20);
    foreach (HostData match in MasterServer.PollHostList())
    {
    GUILayout.BeginHorizontal("Box");

    GUILayout.Label(match.gameName);

    if (GUILayout.Button("Connect"))
    {
    Network.Connect(match);
    }

    GUILayout.EndHorizontal();
    }

    GUILayout.EndArea();
    }


    basically for every server available it create a button and clicking that button will allow user to connect
     
  2. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557
    The most straight-forward way would probably be to instantiate a button prefab for each one, then position it and add an onClick callback through script. I've posted a couple of snippets already that do exactly this; just check my post history if you want to see some code. =)

    EDIT: Post history isn't as easy to scan as I thought; here it is:

    Code (csharp):
    1. for(int i=0; i<5; i++){
    2.     Button btn = ((GameObject)Object.Instantiate(btnPrefab)).GetComponent<Button>();
    3.     btn.onClick.AddListener(delegate{Callback(btn);});
    4. }
    5.  
    6. void Callback(Button btnPressed){
    7.     Debug.Log(btnPressed.gameObject.name + " pressed!");
    8. }
     
  3. ManAmazin

    ManAmazin

    Joined:
    Aug 7, 2013
    Posts:
    246
    alright thanks ill give this a go ...
     
  4. ManAmazin

    ManAmazin

    Joined:
    Aug 7, 2013
    Posts:
    246
    This confuses me a bit..i need to pull from server list all servers that are currently created my previous code allowed to pull the server's name along with a button to connect to that server but that was with the old GUI
     
  5. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557
    Ok, so the new uGUI works quite different than the old OnGUI() stuff. I would strongly advice you to watch Unity's video tutorials on the topic before moving on. After that you'll probably want to keep track of which rooms already have a button, and add and remove buttons as needed using Instantiate() and Destroy().
     
    Aithoneku likes this.
  6. ManAmazin

    ManAmazin

    Joined:
    Aug 7, 2013
    Posts:
    246
    well i watched all the tuts on the new GUI none specify or go over rather, what im looking to do but thanks Senshi im going to try a few things out i know uGUI works differently just got to figure out my switch from old to new in a more complete form
     
  7. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557
    Alright, good luck and feel free to ask if you need any further/ more specific help!