Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Adding to ListBox From Array

Discussion in 'Scripting' started by patmaric, Jan 30, 2020.

  1. patmaric

    patmaric

    Joined:
    Dec 5, 2019
    Posts:
    15
    I got the following code from a YouTube by a brilliant guy, Sloan Kelly. I want to replace the hard-coded names with an array. I have been playing around with it for awhile, but the best I came up with was blank buttons.

    Any ideas?

    public class AddObjectToList : MonoBehaviour
    {
    public ListBox listBox;

    public Sprite warningIcon;

    public void AddButton_Click()
    {
    var buttons = new string[]
    {
    "Fred",
    "Barney",
    "Wilma",
    "Betty",
    "Pebbles",
    "Bam-bam"
    }
    .Select(name => new Dropdown.OptionData(name))
    .ToList();

    listBox.AddOptions(buttons);

    }

    ***********************************


    public void AddOptions(List<Dropdown.OptionData> optionData)
    {
    foreach (var option in optionData)
    {
    // Construct our UI elements
    var copy = Instantiate(itemTemplate);
    copy.transform.SetParent(content.transform);
    copy.transform.localPosition = Vector3.zero;
    copy.transform.localScale = Vector3.one;

    copy.GetComponentInChildren<Text>().text = option.text;

    // Add the event handler
    copy.GetComponent<Button>().onClick.AddListener(
    () => { OnItemSelected(FindIndex(copy)); }
    );

    // Add the option to the list
    options.Add(option);
    }
    }
     
  2. patmaric

    patmaric

    Joined:
    Dec 5, 2019
    Posts:
    15
    UPDATE

    if anyone’s interested, Sloan goes over it here:

     
  3. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,833
    Please use code tags.

    Is the code that you posted the original code that successfully sets "hard-coded" names, or is it your modified version that attempts to use an array but ends up with blank names? (I see an array in there, but the array is initialized using hard-coded values, so both descriptions seem like they would fit.)
     
  4. patmaric

    patmaric

    Joined:
    Dec 5, 2019
    Posts:
    15
    It is the actual code, untouched, which worked.
     
  5. patmaric

    patmaric

    Joined:
    Dec 5, 2019
    Posts:
    15
    Turns out my Unity Scene was apparently broken. After two days of thinking there was some other-worldly concept I was missing, it all came down to removing and redoing a couple of the UI's.