Search Unity

Trying to find a balance with nested coroutines

Discussion in 'Scripting' started by Steamroller, Apr 14, 2016.

  1. Steamroller

    Steamroller

    Joined:
    Jan 2, 2013
    Posts:
    71
    We are trying to stream our world in while you navigate it. We have a number of tiles that load each time you move from one tile to another. At first there was a noticeable hitch whenever you did this but we just refactored the code so that we are using Nested Coroutines.

    The top level starts off with:
    StartCoroutine( foo.Load() ).​

    This load method will the load the content inside itself(ie. the tile) and then will iterate on the children telling them to load:

    foreach childBar in childrenBar:
    yield new StartCoroutine( childBar.Load() )
    So these children load and can have children of their own for as many times as our artists nested the prefabs.

    We finally got this all working, but now all the content takes too long to load cause it happens over too many frames. Is there any way we can batch the coroutines up until some threshold of time has past then wait for the following frame to continue?

    Is this clear?
     
    Last edited: Apr 14, 2016
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    Something like:

    Code (csharp):
    1.  startTime = Time.realTimeSinceStartup;
    2. foreach(childBar in childrenBar) {
    3.     StartCoroutine(childBar.Load()); //no yield
    4.     if(Time.realTimeSinceStartup - startTime > someTreshold) {
    5.          yield return null; //skip a frame
    6.          startTime = Time.realTimeSinceStartup;
    7.     }
    8. }
    Essentially, keep loading children synchronously until some amount of time has passed, and then stop.

    You can set the treshold at some value that seems good, or you could try to vary it based on your frame rate. If you want to stay at 60fps while loading, start out at a treshold of Time.deltaTime - (1 / 60), and then adjust down if Time.deltaTIme slips under (1/60)
     
    Dave-Carlile likes this.