[4.6 UI] ComboBox Buttons return same number?

Each button should return a number respective to where it in the ‘items’ array but when tested with two items, they both return ‘2’?

public class ComboBox : MonoBehaviour {

    public GameObject buttonPrefab;

    public List<string> items = new List<string>();

    int index = 0;

    void Start() {

    }

    public void refresh(int _index) {
        ClearComboBox();
        index = _index;
        Debug.Log("Index = " + _index);
        transform.GetComponentInChildren<Text>().text = TextReader.GetVariable("title", GameModeHandler.GetAddonsPath() + "\\Gamemodes\\" + items[index] + "\\" + items[index] + ".txt");
        int i = 0;
        foreach (string item in items) {
            GameObject btn = (GameObject)Instantiate(buttonPrefab);
            btn.name = btn.name.Replace("(Clone)", "_" + item);
            btn.transform.SetParent(transform.FindChild("Panel"));
            btn.transform.FindChild("Text").GetComponent<Text>().text = TextReader.GetVariable("title", GameModeHandler.GetAddonsPath() + "\\Gamemodes\\" + item + "\\" + item + ".txt");
            Debug.Log(i + " blag");
            //Setting up Triggers
            btn.GetComponent<Button>().onClick.AddListener(
                () => { refresh(i);} **** 'i' is apparently always 2 HERE
            );
            i++;
        }
    }

    private void ClearComboBox() {
        Transform obj = transform.FindChild("Panel");
        for (int i = 0; i < obj.childCount; i++) {
            Destroy(obj.GetChild(i).gameObject);
        }
    }

}

I will answer any questions.

Thanks in Advance :slight_smile:

This is a common trap with loops and lambda. Because the expression is not evaluated until later it uses the final value of i.

Solve by declaring a local scope variable immediately before adding the listener.

int temp = i;