I’m trying to add functionality to my buttons via for loop, because I don’t want to assign them in inspector.
Here is what I’m trying to do:
for (int i = 0; i < players.Length; i++)
{
playersSpellers<em>.spellOne_txt = spellOne_txts*.GetComponent<Text>();*</em>
spellOnePlus_btns_.GetComponent().onClick.AddListener(() => playersSpellers*.AddRemoveSpell(0, adjustSpellCount));
}
And here is what I had to do in order to have it working in Unity
for (int i = 0; i < players.Length; i++)
{_
playersSpellers.spellOne_txt = spellOne_txts.GetComponent();
_}*_
spellOnePlus_btns[0].GetComponent().onClick.AddListener(() => playersSpellers[0].AddRemoveSpell(0, adjustSpellCount));
spellOnePlus_btns[1].GetComponent().onClick.AddListener(() => playersSpellers[1].AddRemoveSpell(0, adjustSpellCount));
spellOnePlus_btns[2].GetComponent().onClick.AddListener(() => playersSpellers[2].AddRemoveSpell(0, adjustSpellCount));
spellOnePlus_btns[3].GetComponent().onClick.AddListener(() => playersSpellers[3].AddRemoveSpell(0, adjustSpellCount));
spellOnePlus_btns[4].GetComponent().onClick.AddListener(() => playersSpellers[4].AddRemoveSpell(0, adjustSpellCount));
spellOnePlus_btns[5].GetComponent().onClick.AddListener(() => playersSpellers[5].AddRemoveSpell(0, adjustSpellCount));
I learned that it has to do something with issues with “loop closures” that are present in .NET v3.5 and that this was fixed in .NET v4.0 (and so my adding listeners using for loop would work as shown above)
I presume we won’t be seeing Unity jump to .NET 4.0 anytime soon, or am I wrong?
Is there a nicer solution at the moment (a workaround) to this?