- Home /
 
Create GUI based on an array
Essentially I want to create a function that I can call that creates GUI buttons based on a string array. Some quick code I came up with is as follows:
 using UnityEngine;
 
               using System.Collections;
public class Example : MonoBehaviour { string[] buttonName = new string[5];
 // Use this for initialization
 void Start () 
 {
 
 }    
 // Update is called once per frame
 void Update () 
 {
     CreateButtons(buttonName);
 }
 
 void CreateButtons(string[] buttonName)
 {
     for(int i = 0; i<5; i++)
     {
         GUI.Button(new Rect(200*i, 0, 200, 50), buttonName);
     }
 }
 
               }
Answer by Apples_mmmmmmmm · Dec 23, 2011 at 04:18 AM
using UnityEngine; using System.Collections;
public class Inventory : MonoBehaviour { string[] buttonName = new string[5];
 // Use this for initialization
 void Start () 
 {
 }    
 // Update is called once per frame
 void OnGUI () 
 {
     for(int i = 0; i<5; i++)
     {
         buttonName[i] = (i+1).ToString();
         GUI.Button(new Rect(200*i, 0, 200, 50), buttonName[i]);
     }
 }
 
               }
Answer by Owen-Reynolds · Dec 23, 2011 at 03:44 AM
Anything using GUI-dot function has to be in the event OnGUI. It's not really an event -- it runs every frame. Be sure to use buttonName[i] and the odd button syntax: if(GUI.Button...) do thing with i. 
Thanks, that helped me clean up my code to what I was trying to accomplish.
Your answer