I have an object that I want to instantiate that contains a button, and I want to spawn any number of them (number of objects is not constant). When the buttons are instantiated, I add ‘onClick.AddListener’ so I can call a function for when they’re clicked. But how do I determine which button called the event? Can I not just have one function that takes in a parameter, e.g. the index of the button in a list I create, to use to identify the button that called it? Because that doesn’t work. An example of what I’m trying to do:
Adding the listener:
buttons[i].onClick.AddListener(delegate { DeleteObject(index); });
And the function:
public void DeleteObject(int index)
{
GameObject.Destroy(objects[index]);
}
However, for some reason this keeps destroying the object at the end of the list, and not at the index. So I can only assume whenever a new button is added it overrides the function with the new index. If so, what is the proper way to do this?