[Unity3d] WaitForFrames in Coroutine

By | May 14, 2015

Advertisement from Google

unityIf you are using Coroutines in Unity3d, you probably know about WaitForSecondsWaitForEndOfFrame and WaitForFixedUpdate classes. Here is an example:

public IEnumerator CoroutineAction()
{
    // do some actions here    
    yield return new WaitForSeconds(2); // wait for 2 seconds
    // do some actions after 2 seconds
}

But sometimes you need to wait for some amount of frames before executing some action. I have created simple class to help you with that:


Advertisement from Google

public static class WaitFor
{
    public static IEnumerator Frames(int frameCount)
    {
        if (frameCount <= 0)
        {
            throw new ArgumentOutOfRangeException("frameCount", "Cannot wait for less that 1 frame");
        }

        while (frameCount > 0)
        {
            frameCount--;
            yield return null;
        }
    }
}

Now you can wait for frames:

public IEnumerator CoroutineAction()
{
    // do some actions here    
    yield return StartCoroutine(WaitFor.Frames(5)); // wait for 5 frames
    // do some actions after 5 frames
}

 

One thought on “[Unity3d] WaitForFrames in Coroutine

  1. Stexe

    The problem I see is that waiting for X frames can vary based on the FPS of the device. When trying to calculate frames it seems to differ slightly (by a few frames) if a device ever drops below 30 FPS or so.

    We’ve been trying to solve a problem by having X frames elapse and then pausing the game — but while it works fine on computers and high end devices that can maintain 30 fps to 60 fps, medium to lower devices will overshoot by a frame or two which throws everything off. Any idea on how to deal with that if there is a way?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *