How to add string to dropdown menu

Hi,

I’m really new to Unity and C# so sorry if my question is a common one but I could not find anything suitable in Google.

I have a dropdown menu and want to add options from a List into it.

if (myEvent.Code == "Hoffenheim Pass")
            {
                dropdownEventIDs.AddOptions(myEvent.Id);
            }

myEvent.Id is a string and the compiler says that I can’t compile a string in System.Collections.Generic.List<UnityEngine.UI.Dropdown.OptionData>

What do I have to do to add my IDs (string) to the dropdown menu?

Look at the documentation for the Dropdown.AddOptions call’s arguments.

You’ll notice three varieties of things you can pass in: a list of strings, a list of sprites, or a list of “Dropdown.OptionData” objects, whatever those are.

If you are just adding a single string, you probably just need to make a list out of that string ( a list of one thing) and pass that in.

The C# syntax for that sort of “transient” list looks like:

dropdownEventIDs.AddOptions( new List<string> { myEvent.Id}  );

That’s the general layout for an initializer for making a list of strings, and you are supplying only one string to it, then immediately passing it into AddOptions.

This is also presuming that your identifier dropdownEventIDs is actually a single Dropdown object, but it also ends with an “s”, making me think it might be a list, not just a single object. If it is a bunch of dropdown objects (list or array) then you would need to dereference it first.

Thanks for your fast answer. You’re presuming it right.
I adapted the code to the following and it works now. Thanks

        var options = new List<string>();
        foreach (var myEvent in events)
        {
            if (myEvent.Code == "Hoffenheim Pass")
            {
                options.Add(myEvent.Id);
            }
        }
        dropdownEventIDs.AddOptions(options);
1 Like