I have problems capturing a variable in a closure.
My code looks like this:
BetterList<Action> actions = new BetterList<Action>();
for (int i = 0; i < 7; i++) {
var innerCopy = i;
Action action = new Action(delegate {});
action += delegate () {
Debug.Log("I am action number " + innerCopy);
};
actions.Add(action);
}
foreach (Action action in actions) {
action();
}
The last loop will output “I am action number 6” seven times.
I don’t really understand why innerCopy
isn’t captured by the closure! Especially because this code I presented is exactly the same as an accepted answer to the same problem:
So I am a bit confused, did I do something wrong, or is there some kind of bug in the Unity/.net environment that causes this behavior?
EDIT:
Thanks to Bunny83, I tried my code in a new empty project, and it worked flawlessly.
But now I discovered how to reproduce my error:
IEnumerator ProduceError() {
BetterList<Action> actions = new BetterList<Action>();
for (int i = 0; i < 7; i++) {
var innerCopy = i;
Action action = new Action(delegate {});
action += delegate () {
Debug.Log("I am action number " + innerCopy);
};
actions.Add(action);
}
foreach (Action action in actions) {
action();
}
yield return new WaitForEndOfFrame();
}
void Awake () {
StartCoroutine(ProduceError());
}
Somehow the coroutine screws the closures up.