1

I have a ScrollView with a Grid Layout Group component on the Content object :

enter image description here

My item list is inside the Content object and each item own a Button component.

I'm trying to add the onClick programmatically to handle a lot of objects and index with a parameter like this :

        int i = 0;
        foreach(Button btn in scrollViewContent.GetComponentsInChildren<Button>()) {
            btn.onClick.AddListener(() => Load(i));
            i++;
        }

However onClick I always get the last index + 1 on all item click. Here are my logs :

enter image description here

Until Log 44, this is the foreach print loop and the Log "index : 45" is the result on click.

So two question :

• Why all item click return the same index ?

• How can I get index 45 whereas the i var stopped at 44 ?

1
  • as you didnt share the code with the debug log in, its hard to know but if there are 0-44 items, after the 44th item i will be 45.. Commented Nov 21, 2023 at 20:06

1 Answer 1

1

The issue is that the callbacks all use the same variable. This may seem odd since an int is a value type and must be copied. However, the variable is captured in the local scope, resulting in the same variable being used across all callbacks.

To solve the issue, create a new local variable inside of the foreach loop.

var i = 0;

foreach (var button in buttons)
{
    var index = i++;

    button.onClick.AddListener(() => Load(index)); 
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.