Index out of range when using delegates to set onClick at runtime

I am writing a script that passes 2 arrays into a menu creation method- the arrays hold the text and the models (which the buttons spawn) for the buttons that the menu will create. However, due to the fact that I would like to make the whole thing dynamic I need to set all the references to the gameobjects at runtime.

Below is the method which sets up the panel with buttons

public void Choice(string upgradeQuestion, /*List<UnityAction>*/ string[] upgradeText, GameObject[] buildings)
{

    Button[] buttonList = null;
    buttonList = new Button[upgradeText.Length];
    modalPanelObject.SetActive(true);
    for (int i = 0; i < upgradeText.Length; i++)
    {
        Button newbut = Instantiate(button);
        Debug.Log(newbut);
        newbut.transform.SetParent(buttonPanel.transform);
        buttonList *= newbut;*

//Remove previous listeners
buttonList*.onClick.RemoveAllListeners();*
//Add Panelclose listener
AddOnClickListener(buttonList*, ClosePanel);*
//Add Custom Listener
Debug.Log(buildings*);*
buttonList_.onClick.AddListener(delegate { BuildingPlacer(buildings*); });
buttonList.GetComponentInChildren().text = upgradeText;
Debug.Log(“button created”);
}
this.question.text = upgradeQuestion;
this.iconImage.gameObject.SetActive(false);
foreach (Button b in buttonList)
{
b.gameObject.SetActive(true);
}
}
The problem is that
buttonList.onClick.AddListener(delegate { BuildingPlacer(buildings); });*

returns an IndexOutOfRangeException when the buttons are clicked. The arrays are not empty and are of the same size, the buttons get created but the issue lies when the onclick is assigned.
Any idea why i am getting an index out of range_

The whole loop is run to completion when you call this method, after that, at some point you press the button, and by then the value of i is upgradeText.Length because that’s the exit condition for your loop.

When you use delegates or such in this manner, the variable i gets wrapped into the delegate rather than just its value, making it sort of act like a reference type.

It should be easily fixable by passing a variable you don’t change later into the delegate.

var i2 = i;
buttonList*.onClick.AddListener(delegate { BuildingPlacer(buildings[i2]); });*