Add Custom Argument to On Click() Event of a button


I want to spawn multiple instances of this button and they are all supposed to have a different ID in this field. Do I have access to it at runtime?
I know that I can go by the button’s name, but that seems like a hack, since I have to parse it.

EDIT: I found the PersistenListener section of the Unity docs, but they only seem to be accessable in the editor, correct?

You’re better off leaving that OnClick list empty in the editor and just adding the entire listener in code using myButton.onClick.AddListener(..)

Alternatively, assign that listener to a parameterless function that reads the int value you need from somewhere else.

I am using

MyButton.onClick.AddListener(delegate { OnMyButtonClick(MyButton); });

However that doesn’t tell me which ID has invoked the OnMyButtonClick. The number of buttons is supposed to be dynamic, so I cannot create one delegate for each button. I also don’t see a way to store the indices globally whithout some sort of look-up table.
As I said, I could store the index in the button’s name, but I would really like to pass an int, since it’s supposed to direct to the index of an array. Also ideally I want to be able to easily exchange the ID of each button.

A few ideas off the top of my head:

  • use the transform.GetSiblingIndex() of the button
  • use a Dictionary<Button, int>() that you populate when you instantiate the button (the lookup table you mentioned)
  • Attach another component to the button and populate an int field on that component when you instnatiate the button. Then since your button is an argument to OnMyButtonClick, you can GetComponent that second component and read the int from there

Yeah, I had similar ideas (the dict is basically what I meant by “lookup table”). They are all a workaround and I don’t like them, but I think dict is the way to go.
GetComponent is slow and I need an additional MonoBehaviour.
The sibling index is a good idea, but the buttons have their own parents (always come in pairs)
Thanks.

Addendum: I needed to be able to adjust the index a button has, because whenever I delete one, the ones below have to move up. However the Value of a KeyValuePair is readonly, so I ended up creating a new class for this that holds the index. Now I can easily adjust it and even was able to re-allocate some functions from the class managing the UI Behaviour.