Button.onClick.AddListener; How to Pass parameter or get which button was Clicked in Handler Method

How to pass a parameter or get which button was clicked in button.onClick handler method?

void Start ()
{
    buttonPre.onClick.AddListener( SwitchButtonHandler );
    buttonNext.onClick.AddListener( SwitchButtonHandler );
}
  
void SwitchButtonHandler ()
{
    //Here i want to know which button was Clicked.
    //or how to pass a param through addListener
}

(please look at the comment)

Try this :

void Start ()
{
   ButtonPre.onClick.AddListener( delegate{SwitchButtonHandler(0);} );
   ButtonNext.onClick.AddListener( delegate{SwitchButtonHandler(1);} );
}

void SwitchButtonHandler ( int idx_ )
{
   //Here i want to know which button was Clicked.
   //or how to pass a param through addListener
}

You can also do multiple in the brackets like this.

btn.onClick.AddListener(
    () => { Function(param); OtherFunction(param); }
);

In my case the solution was

for( int i=0 ; i<buildings.Length ; i++ )
{
    var i1 = i;
    button.onClick.AddListener( () => SelectBuilding(i1) );
}

You can use:

gameobject.GetComponent<Button>().onClick.AddListener(
    () => Method(5)
);

Or:

gameobject.GetComponent<Button>().onClick.AddListener(
    new UnityAction(() => Method(5)
);

Some Mehod:

void Method ( int i )
{
    Debug.Log(i)
}

Late to the party, but still relevant. I was looking for something similar in C# and realized I could just cache the enumerated KeyCode list into a Dictionary. So:

public static readonly Dictionary KeycodeCache = new Dictionary();

void FillKeyCodeLookup()
{
    foreach( KeyCode code in Enum.GetValues(typeof(KeyCode)) )
    {
        KeycodeCache.Add( code.ToString() , code );
    }
}

internal static KeyCode GetKeyCode ( string codeName )
{
    // Get from cache to prevent unnecessary enum parse
    return KeycodeCache[codeName];
}

Simply fill the Dictionary at Awake or Start and call the Dictionary.

Seriously, thanks for saving me a massive headache @ZMarco. :smiley:
Because I wanted to start bashing my head against the wall after trying multiple methods without avail, trying to achieve this exact thing.

First I tried to have an int value outside the loop that would increment. Wouldn’t work and always pick the last index. And then I tried it by having a list and array holding those indexes, and then it would return a null reference. I just don’t understand why having a var of the index would logically work. I’m so confused about that.

Try this:

for( int index=0 ; index<_LevelBtn.Count ; index++ )
{
    System.Action action = (index) =>
    {
        _LevelBtn[index].onClick.AddListener(
            () => { OnLevelButtonClicked(index); }
        );
    };
    action(index);
}