Hi, I was trying to create a script to generate buttons dynamically. I sucessfully managed to do that by following the answers to this question:
https://answers.unity.com/questions/875588/unity-ui-dynamic-buttons.html
The code I got from here was something like this:
Button tempButton = SelectWeaponButton.GetComponent();
tempButton.onClick.AddListener(() => ShowWeapons());
for(int i = 0; i < AvailableMissiles.Length; i++)
{
GameObject b = Instantiate(WeaponButtonPrefab);
b.transform.SetParent(WeaponButtonParent.GetComponent());
b.GetComponent().anchoredPosition = new Vector2(0, -(UIOffsetY*i+UIOffsetY));
Button btn = b.GetComponent();
int tempInt = i;
btn.onClick.AddListener(()=>SetCurrentWeapon(tempInt));
}
This works perfectly well. SetCurrentWeapon function for now only prints "tempInt" to debug.log. In this case, button created when i was 0, shows 0. Button created when i was 1, shows 1.
But then I tried to eliminate the additional step of storing "i" in "tempint", by directly using i in the next line. So code became something like this:
Button tempButton = SelectWeaponButton.GetComponent();
tempButton.onClick.AddListener(() => ShowWeapons());
for(int i = 0; i < AvailableMissiles.Length; i++)
{
GameObject b = Instantiate(WeaponButtonPrefab);
b.transform.SetParent(WeaponButtonParent.GetComponent());
b.GetComponent().anchoredPosition = new Vector2(0, -(UIOffsetY*i+UIOffsetY));
Button btn = b.GetComponent();
btn.onClick.AddListener(()=>SetCurrentWeapon(i));
}
But now all all button pass "2" to SetCurrentWeapon function (there are 2 buttons, when 3 buttons are there, they will all pass 3).
This is something I found weird. 'i' and 'tempInt' hold the same value, don't they? so why does the code work correctly when we run it by storing the value of i in tempInt first, but all show same value (which is equal to total number of buttons) when we try to use i directly?