Saralyn
Saralyn

Reputation: 313

How to tell an event handler method who called it in Unity

I would like to use the same method as an event handler for multiple dropdowns. In order for part of the method to work, they must know who called them - either the name of the dropdown or the title it stores as its first value. I know that I could create an individual method for each one of these dropdowns, but that seems excessive. Is there a way to do something along the lines of

OnClick(int indexSelected, string dropdownTitle)

?

Upvotes: 0

Views: 406

Answers (1)

Programmer
Programmer

Reputation: 125255

I would like to use the same method as an event handler for multiple dropdowns.

You can pass the Dropdown instance as parameter with the help of delegate then compare which one it is by the instance, name or which ever property you prefer.

public Dropdown dropdown;

Dropdown otherDropDown;
void OnEnable()
{
    //Register to onValueChanged Events
    dropdown.onValueChanged.AddListener(delegate { callBack(dropdown); });
}

void OnDisable()
{
    //Un-Register from onValueChanged Events
    dropdown.onValueChanged.RemoveAllListeners();
}

void callBack(Dropdown currentDropdown)
{
    //Compare dropdown by instance?
    if (currentDropdown == otherDropDown)
    {
        int value = currentDropdown.value;
    }

    //Compare dropdown by name
    if (currentDropdown.name == "YourDPName")
    {
        int value = currentDropdown.value;
    }
}

Upvotes: 1

Related Questions