WaitForSecondsRealTime, Declare once and use many times?

Hello everyone.

I remember reading somewhere that objects declared for suspending coroutines such as WaitForSeconds, WaitForSecondsRealTime should be declared once before a loop and the declared yield object should be used in following iterations. I remember it was about getting rid of unnecessary GC allocations.

But, here is a weird behaviour as far as I can grasp things :slight_smile:

    private IEnumerator SomeCoroutine()
    {
        float yieldReturnInterval = 0.1f;
        WaitForSecondsRealtime waitForSecondsRealTime = new WaitForSecondsRealtime(yieldReturnInterval);

      // Do some stuff here.

        while (remainingDuration > 0)
        {
            remainingDuration -= yieldReturnInterval;
            yield return waitForSecondsRealTime;
        }

        // Do some other stuff here.

        SomeFancyFunction();
    }

First one above is what I understand from “declare once and use it as much as you can” advice. :slight_smile:
But loging the time in console, I can clearly see that remaining time reaches 0 much faster than intended time.
Code below works fine, but I have to create a new WaitForSecondsRealTime object per iteration of while loop. So, what do you think the problem could be here? (Or where did I misunderstand things :slight_smile: )

    private IEnumerator SomeCoroutine()
    {
        float yieldReturnInterval = 0.1f;
      // Do some stuff here.

        while (remainingDuration > 0)
        {
            remainingDuration -= yieldReturnInterval;
            yield return new WaitForSecondsRealTime(yieldReturnInterval);
        }

        // Do some other stuff here.

        SomeFancyFunction();
    }

I believe it’s because you have to waitForSecondsRealTime.Reset() each time in that loop if you actually want it to wait that much time “each time”. Otherwise, in your first example, on the very first iteration of the loop, it’s going to wait the desired time and be in a finished state, and thus each consecutive call to yield to it will simply result in a 0 wait time.

Hmm where would be the correct place to… place it? :slight_smile:
I tried putting it at the top of the while block like following:

        while (remainingDuration > 0)
        {
            waitForSecondsRealTime.Reset();
            remainingDuration -= yieldReturnInterval;
            yield return waitForSecondsRealTime;
        }

But that doesn’t seem to make a difference.

I’m having this issue as well. Creating a new every loop works fine, but reusing does not (even when calling reset at end of loop). I waits the specified amount of time, then loop repeat as if it wasn’t there anymore.