Methods to avoid game freezes when working with for loops

If you put a lengthy for loop in your starting function (for example, several for loops being used to generate a map at the start of the game), the game freezes until the for loop(s) is completed. How do I avoid this?

1 Answer

1

You could yield for a frame so the rest of the game can update and then resume the work the next frame. You can yield in Start too. e.g.

Instead of:

void Start()
{
  // really long initialization operation
}

You can do:

IEnumerator Start()
{
  for( ... )
  {
    // do a bit of work
    yield return null;  // this yields for 1 frame
  }
}

That is C#; the JavaScript syntax is different (and apparently simpler).

Ah, that sounds good. Thanks. :)