delegate void bug?

Hello! I had some issues adding events with parameters to a unity UI button in a cycle, my initial code was:

for( int starN = 0 ; starN < _missionStars.Length ; starN++)
{
  Button missionButton=_missionStars[starN].gameObject.AddComponent<Button>();
  missionButton.onClick.AddListener(delegate{OnPressNew([B]starN[/B]);});

}

this didn’t work correctly - each button had the same value ( equal to _missionStars.Length)
after much consternation, I finally got it to work by adding this line:

for( int starN = 0 ; starN < _missionStars.Length ; starN++)
{
Button missionButton=_missionStars[starN].gameObject.AddComponent<Button>();
 int misisonIndex=starN;
  missionButton.onClick.AddListener(delegate{OnPressNew(misisonIndex);});

}

is this a bug in unity or am I unaware of some programming concept/intricacy?

This isn’t a bug, but involves some not initially intuitive behavior with closures. The article Closing Over the Loop Variable by Erik Lippert has a thorough discussion on the topic. Also, this behavior was changed in later versions of C# which haven’t yet made it into Unity.

And your solution is the solution. You have to “capture” the loop variable inside the body of the loop in order to retain the value for that iteration.

thanks Dave! So from what I understood it assigns a sort of “pointer” to the value of the loop (which makes it the last value),
thanks for the quick explanation!