Search code examples
c#unity-game-enginedropdown

Unity - one Dropdown callback for multiple Dropdown components


I have a UI with a number of dropdown controls, each affecting one of an array or items. I use onValueChanged(int index), each hooked up to its own listener (selected01(), selected02() ... etc).

This is a bit messy. It would be much better to have one callback - selected(Dropdown instance, int index) - which handles all of them. The callback would identify the control from the instance parameter and act on the appropriate array item.

I cannot see how to do that - onValueChanged() only provides an index not the source. Yet I am sure I have seen a solution to this, possibly involving a Delegate, but cannot now find it.

Any suggestions? (The same could apply to any array of controls, not just Dropdowns).


Solution

  • As far as I could see onValueChanged anyway returns the instance of DropDown that was changed.


    Maybe that is different in the version you are using.

    You can simply create your own listener method and do e.g.

    public DropDown[] dropdowns;
    
    private void HandleChange(DropDown dropdown, int newIndex)
    {
        // Your stuff here
    }
    
    ...
    
    foreach(var dropdown in dropdowns)
    {
        var currentDropdown = dropdown;
        currentDropdown.onValueChanged.AddListener((newIndex) => { HandleChange(currentDropdown, newIndex); });
    }