- Home /
Adding Buttons to a list
hello, I have what I think is an easy procedural question that I can't quite pin down. I'm trying to make a list of buttons and creating the list itself is fairly easy. I just have
public List<GameObject> button_list = new List<GameObject>();
now the problem I have is adding new buttons to the list. I tried doing
button_list.Add(new GameObject (Button));
but unity threw 5 errors at me so clearly it doesn't like this.
I'm not too worried about creating the game object itself as I'll do that procedurally myself for now. I just need the game object variable in the script so I can attach them to the game objects I create in the game and then be able to iterate through the list so I can do things to the buttons.
Answer by MacDx · Jan 31, 2018 at 07:27 PM
To create a game object using the GameObject's class constructor with a button script attached you would do it like this:
button_list.Add(new GameObject ("ButtonName",typeof(Button)));
Or you could also do it like this:
GameObject newButton = new GameObject();
newButton.name = "ButtonName"; //Optional
newButton.AddComponent<Button>();
button_list.Add(newButton);
Or you could have a prefab that already contains a Button script and just do:
//Having previously defined and assigned a public GameObject buttonPrefab; field
button_list.Add(Instantiate(buttonPrefab));