Add button listener via for loop

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?

for (int i = 0; i < players.Length; i++)
{
var ps= playersSpellers*;*
Text t = spellOne_txts*.GetComponent();
ps.spellOne_txt = t;
var clickEvent = spellOnePlus_btns.GetComponent().onClick;
clickEvent.AddListener(() => ps.AddRemoveSpell(0, adjustSpellCount));
_}*
By using a local variables, you should be able to bypass the issue. At least, I do it like this and it works for me._

I decided to accept fafase’s answer, because the idea is good, even though fafase put into local variables members of spellOne_txts, that is not neccessary at all.

I formatted my code a bit more nicely :slight_smile: so this is what I used:

for (int i = 0; i < players.Length; i++)
    {
      playersSpellers<em>.spellOne_txt = spellOne_txts*.GetComponent<Text>();*</em>

var tempPlayerSpeller = playersSpellers*;*

var tempSpellOnePlusButton = spellOnePlus_btns*.GetComponent();
tempSpellOnePlusButton.onClick.AddListener(() => tempPlayerSpeller.AddRemoveSpell(0, adjustSpellCount));
_}*_

Thank you @fafase for providing such a simple and concise answer to a problem that I have been struggling with for months.