- Home /
Bug with Unity Compiler with Lambdas?
I've been trying to figure out a weird Unity issue and I think I got a small piece of code that will repro this. I create 2 actions that should together set both entries of a bool[2] array to true. Even though the actions are deferred, the 'capture' value should catch the current value of 'i'.
void Start ()
{
// Don't use StartCoroutine... I'm trying to eliminate as many points of failure as possible
var test = Test ();
while (test.MoveNext()) { }
}
private IEnumerator Test()
{
Action[] actions = new Action[2]; // Set up 2 actions
bool[] ticked = new bool[2]; // The actions will set these to true when they are run
// Create the actions but don't execute them
for (int i = 0; i < 2; i++)
{
int capture = i;
actions[capture] = () => ticked[capture] = true;
}
// Execute actions
for (int i = 0; i < 2; i++)
{
actions[i]();
}
// Check which entries got ticked
for (int i = 0; i < 2; i++)
{
Debug.Log(i + ": " + ticked[i]);
}
yield return null;
}
The output is:
0: False 1: True
I thought I was going crazy so I tried 2 things:
1) I put the exact same code in Visual Studio in a console app. The result is both ticked entries are true.
2) I did this again in Unity but just put it in a plain old void method and just executed it directly from Start. Both entries are ticked.
I can only think that this discrepancy is due to a quirk with how variables are captured in an enumerator in Unity.
Can someone confirm?
I'm seeing the same results over here (false/true with enumerator, true/true without). Huh.
for (int i = 0; i < 2; i++)
{
int capture = i;
actions[capture] = () => ticked[capture] = true;
}
I'm confused by this. I would have thought that running the action would then use the value of capture at the time the action is run. You're actually calling the function "ticked[capture] = true;" when you run the action, I thought. Capture falls out of scope, the last known value is 1 (which persists because...reasons. probably coroutine manager caching ALL local variables), so you get 0:false and 1:true.
I'm surprised it works in visual studio (but I'm not a lambda expert when it comes to shenanigans like this).
So in summary, my guess is that capture is stored in the coroutine as a variable local to the function, not the for block, so when you invoke the actions later they still have access to capture and aren't using the values from before.
Thanks for checking.
Loius, this behavior is mentioned in the C# spec. See http://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp for an example. Each action has a reference to its own copy of 'capture' since 'capture' falls out of scope after EVERY iteration of the for loop.
This should work and it even works in Unity... sometimes. Just not in my example above.
It seems like the combination of IEnumerators and variable capture is causing the compiler problems.
Your answer
