How to determine which button triggered onClick Listener event

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?

You’ve got the wrong forum, this is the 2D forum. The UI forum is here.

I’ll move your post for you.

Had the same problem some time ago. When you set the delegate it points to the same address in memory (I think?). Just use a temporary variable:

int temp = index;
buttons[i].onClick.AddListener(delegate { DeleteObject(temp); });

I think this should work.