Strange behaviour with AddListener inside a loop


Hi! I just wanted to share a strange behaviour that I got while making my game, that might be useful for everyone. So the long story short is that I was implementing a 'roguelike' skill selection screen. I created a method to get some random skills to show. This is the pseudocode for Unity:

Skills[] listSkill;

float[] values;

listSkill = MethodToGetRandomSkills(out values)

for(int index = 0; index < subsetOfListSkill; index++)

{

    button[index].OnClick.AddListener(

    delegate {

            ApplyThisSkillToPlayer(listSkill[index], values[index]);

    })

}

The problem was related to the delegate part, I was getting bad values, applying different skills and values. Not the one I selected. Then I found this explanation about using 'Addlistener' in a loop: https://answers.unity.com/questions/1195925/when-using-addlistener-can-multiple-...

I tried the local variable fix and it works when I called the method for the first time:

for(int index = 0; index < subsetOfListSkill; index++)

{

    Skill tempSkill = listSkill[index];

    float tempValue = values[index];

    button[index].OnClick.AddListener(

    delegate {

            ApplyThisSkillToPlayer(tempSkill, tempValue);

    })

}

After other calls of the method, I was getting other strange behaviours. At the end, I solved it by not using AddListener, but storing the selected skills and values in a global array. And calling the method using the 'OnClick' on the Unity Editor, not from the code.

Leave a comment

Log in with itch.io to leave a comment.