Adding delegate to button click behaves weirdly?

Here is a demonstration of my problem.

[SerializeField] List<Button> Buttons;
    void Awake()
    {
        for (int i = 0; i < Buttons.Count; i++)
        {
            var button = Buttons[i];
            button.onClick.AddListener(delegate { OnButtonClicked(i); });
        }
    }
    void OnButtonClicked(int i)
    {
        Debug.Log("index is " + i);
    }

No matter which button I press, debug returns the count of the list.

Shouldn’t it return the index of the button from the list? What am I missing here?

Delegate / Action variable capture / value capture:

A very nice summary by Bunny83;

2 Likes

This is really good information. Thanks.