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.
Silent Wings 2491
silent Wings 2491 is a lite scrolling shoot'em up with some roguelike elements & #MyFirstGameJam submission
Status | In development |
Author | tmseldon |
Tags | Arcade, mfgj14, My First Game Jam, Retro, Voxel |
Languages | English |
More posts
- Fixed small bugAug 16, 2022
- Final implementation and playable demo!Jul 17, 2022
- Demo version playable!Jul 16, 2022
- Enemy developmentJul 12, 2022
- Player's experience & first implementationsJul 07, 2022
- Game ConceptJul 04, 2022
Leave a comment
Log in with itch.io to leave a comment.