Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Alan Tang · Jul 28, 2014 at 06:00 AM · bugyieldcompilercapture

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?

Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image rutter · Jul 28, 2014 at 06:07 AM 1
Share

I'm seeing the same results over here (false/true with enumerator, true/true without). Huh.

avatar image Loius · Jul 28, 2014 at 06:09 AM 0
Share
       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.

avatar image Alan Tang · Jul 29, 2014 at 12:35 AM 1
Share

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.

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Invoke and Yield fail together- bug or feature? 1 Answer

Are coroutines freezing my game? 0 Answers

Bug hunting in the code... 1 Answer

my mistake or bug? Unity compiler error 0 Answers

Microsoft vs Mono C# compiler initialisation differences. Is this a bug in Mono? 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges