Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Coroutine yield clears dictionary

Discussion in 'Scripting' started by Vertnacular, Mar 2, 2018.

  1. Vertnacular

    Vertnacular

    Joined:
    Oct 15, 2017
    Posts:
    12
    So I created a coroutine to create a number of objects over a given period of time to prevent one giant creation process in one frame and thus having a lag spike. I thought I'd be smart about it and have the coroutine only wait for x amount of time or just until the end of the frame if the process time was taking too long by checking deltatime against a threshold like so:

    Code (CSharp):
    1. processTime += Time.deltaTime;
    2.                 if (processTime > dynamicWaitThreshold)
    3.                 {
    4.                     processTime = 0;
    5.                     yield return new WaitForEndOfFrame();
    6.                 }
    Well anyway, I have a dictionary filled with info that I use for the creation of these objects. I started to get some errors later in the code where I use the dictionary again. So I logged the count of the dictionary and is was 0. I checked my code to make sure I wasn't clearing or overwriting it, but I didn't see anything. So I commented out the "yield return new WaitForEndOfFrame()" and the dictionary count was greater than 0 again. I wondering if yielding from some reason clears a dictionary or is there some low level memory thing going on? If anyone has any suggestions, I would appreciate it very much.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,186
    No, the coroutine doesn't clear the dictionary. You probably have something else going on.
     
  3. Vertnacular

    Vertnacular

    Joined:
    Oct 15, 2017
    Posts:
    12
    Well I kind of discerned that o_O but one would assume that the problem is in the "yield return new WaitForEndOfFrame()" since commenting it out causes the dictionary count to not be 0. I'm just wondering why having a yield will clear a global dictionary.
     
  4. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,462
    It doesn't. That's not the cause. Look for references to the dictionary and track when they're executed. Could even be a sequence-of-events issue depending on when this is run.
     
  5. Vertnacular

    Vertnacular

    Joined:
    Oct 15, 2017
    Posts:
    12
    Okay got it! It was down to how I created the dictionary (as it's always the problem with these kind of things). The dictionary wasn't a copy of another dictionary but rather a reference. So when the code would yield, the reference would be lost and thus an empty dictionary! Thanks!