Hi, I’m wondering how exactly I could go about making a dynamic dropdown menu for a really big gameobject array I have.
I made 107 gameobjects for a building game prototype I recently started. I loaded them all into a GameObject array called ghosts, and i can cycle through them by changing the value of the array, like ghosts[0] to ghosts[1] or ghosts[2] etc.
I am wondering if there is a way to put these objects into a ui dropdown list, and most importantly if i can set each dropdown option to change my array value, so if I click the third down option in the list it can change ghosts[0] to ghosts[2].
I’m open to whatever suggestions anyone comes up with, I just don’t know exactly how to do this.
You can use something like this to programatically populate a Dropdown:
void PopulateDropdown (Dropdown dropdown, GameObject[] optionsArray) {
List<string> options = new List<string> ();
foreach (var option in optionsArray) {
options.Add(option.name); // Or whatever you want for a label
}
dropdown.ClearOptions ();
dropdown.AddOptions(options);
}
usage:
Dropdown myDropdown;
GameObject[] dropdownObjects = GameObject.FindGameObjectsWithTag ("PowerUp"); // For example
PopulateDropdown (myDropdown, dropdownObjects);
Note: This can be pretty slow if you have a ton of items. Because Dropdown.AddOptions()
doesn’t get rid of any existing options, you may be able to do this one item at a time in a coroutine as opposed to doing it all at once.
You can use AddOptions()
method to add dropdown options dynamically. There we have specify a list of string that needs to display on the dropdown.
[SerializeField]
Dropdown dropdown;
public void Start() {
List<string> options = new List<string> () { "Option1", "Option2", "Option3" };
AddDropdownOptions(dropdown, options);
}
void AddDropdownOptions(Dropdown dropdown, List<string> options) {
dropdown.ClearOptions ();
dropdown.AddOptions(options);
}