Dynamic button OnClick Listener incorrect values

Must be fairly obvious, but I just can’t see it. So help a guy out :slight_smile:

// Assign new listeners
// objectPrefabsCount = 3

for (int i = 0; i < objectPrefabsCount; i++)
{
    Debug.Log("object index = " + i);

    objectButtons[i].onClick.AddListener(() => _LE.SpawnObject(_LOC.GetCategoryIndex(), i));

    Transform child = objectButtons[i].transform.Find("Icon");

    if (child != null)
        child.GetComponent<Image>().sprite = _LOC.GetIcon(_LOC.GetCatIndex(), i);
}

Debug for above:

Debug value when I actually click on each of the generated buttons.
Category is correct, object is not:

This part is however displaying the correct images:

Transform child = objectButtons[i].transform.Find("Icon");

    if (child != null)
        child.GetComponent<Image>().sprite = _LOC.GetIcon(_LOC.GetCatIndex(), i);

The variable ‘i’ is being used for the lambda expressions, so all of them close over the same variable and that exact variable will be accessed when you read from it and write to it.

In order to fix the “problem”, you can create a local variable within the loop, assign i’s value to it and use that for the lambda expression.

2 Likes

I’m not really familiar with lambda expression, kind of a new thing for me.
Works like a charm, thanks :slight_smile: