Button.onClick.AddListener() not saving function arguments correctly

Hi I have a code that looks something like this

for(int i = 0; i < currentTabButtons.Count; i++) {
       currentTabButtons[i].onClick.AddListener(()=>SetTab(i));
}

However, they’re all using the last value of i instead, which is the number of elements in the currentTabButtons list. (e.g if there are six elements, all buttons would do SetTab(6))

I tried doing a workaround which involves putting an integer instead of a variable as the argument and it now works as intended.

What was I doing wrong with the first script?

Looks like the same answer from a similar thread might apply here:

It works perfectly! Thanks a bunch!!!

1 Like