Calling functions on dropdown menu value change (from script, not inspector)

Hello folks. Still rather new to Unity and C# in general. I’m trying to generate two drop down menus (independent, they have nothing to do with each other) via script, not from the editor.

I’ve got something like

public class myClass : MonoBehaviour
{
    private Dropdown.DropdownMenu myDropdown = new Dropdown.DropdownMenu();
    void Start()
    {
        populateList();
    }
    void populateList()
    {
        List<Dropdown.OptionData> myList = new List<Dropdown.OptionData>();
        myDropdown = gameObject.AddComponent<Dropdown>();
        for(int i = 0; i < 6; i++)
        {
            myList.Add(new Dropdown.OptionData(i.ToString()));
        }
        myDropdown.AddOptions(myList);

        //now I need to tell it what to do when the value changes
        //I'd like to have myFunction() called
        //myDropdown.onValueChanged = ???????
    }
    void myFunction()
    {
        Debug.Log("Value changed!");
    }
}

(forgive me if that doesn’t work if you copy and paste it. My actual code is quite a bit more extensive but I’ve tried to edit out what’s not relevant to the dropdown thing. hopefully you get the idea of what i’m trying to do)

I’ve tried reading about UnityEvents and DropdownEvents and UnityActions but I don’t really understand how it all fits together. I just need a particular function called when the value of the dropdown is changed. I’m aware I’ve probably omitted some stuff for actually drawing the dropdown into a GUI, but I do know how to do that. It’s just the function calling I’m confused about.

onValueChanged is a UnityEvent with an int parameter.

Dropdown d;
d.onValueChanged.AddListener(DoSomething);

private void DoSomething(int arg0)
{
    // do something
}
1 Like

Thanks! Ended up using something like:

void setRes(int arg0)
    {
        Debug.Log("Resolution changed");
    }
void populateResList()
    {
        resDropdown = gameObject.AddComponent<Dropdown>();
        for(int i = 0; i < 6; i++)
        {
            resList.Add(new Dropdown.OptionData(resText[i]));
        }
        resDropdown.AddOptions(resList);

        UnityAction<int> resAction = new UnityAction<int>(setRes);
        resDropdown.onValueChanged.AddListener(resAction);
    }