[SOLVED] Loop through array one element per frame continuously.

I’ve got this array of size 128. It needs to be updated frequently. But rather not all of it during one frame, every frame.

My first idea was to use coroutines. But it rather quickly fell apart.

Anyone have any idea how to approach this the ‘proper’ way?

Coroutines.

IEnumerator UpdateArray()
{
  int index = 0;

   while(true)
   {
      yield return new WaitForEndOfFrame();

      UpdateArray(index);

      index = (index < array.Length) ? index + 1 : 0;
   }
}

;

Might as well just use Update if you’re doing that.

void Update () {
    UpdateArray (index++ % array.Length);
}

This does make the code framerate-dependent, though.

–Eric

Thanks for the help! will try both ways.

If you dont mind making it a hair more complicated you could scale the amount of entries processed per frame based on the frame rate or delta time, so you don’t get the scenario where a low fps causes it to take a full 3-5 seconds to do them all and big noticeable delays to the user.

I’m assuming these must be very intensive operations to perform for each entry if they need to be split across multiple frames? What exactly are they doing?

It’s only modifying some classes inside. Nothing super heavy.
I just thought it’d be a good thing to learn and be able to use when it’s definitely required.

The coroutine solution was just as framerate dependent!
I kinda like that the coroutine way hides the indexer as a part of the coroutine rather than having it be a field. Otherwise they’re equivalent.

Yes, as I noted. Using an actual separate thread would probably be best, assuming the code doesn’t need to access the Unity APIs.

–Eric