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

Please look at the commont.

    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
    }

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:
private 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();
private 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.

Try this :


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