Implementation of WaitForSecondRealtime with CustomYieldInstructoin.

Hi.

I cannot seem to get my head around the implementation of WaitForSecondRealtime with CustomYieldInstructoin. Would really appreciate tips to the code. The Debug.Log(“after pause…”) never runs.

public class Test: MonoBehaviour {

void Update() 
{ 
     if(flag) {
          StartCoroutine(Pause(5f));
          SceneManager.LoadScene("NextScene");
     }
 }

IEnumerator Pause(float p)
{
    Debug.Log("pause...");
    yield return new WaitForSecondsRealtime(p);
    
    Debug.Log("after pause..");
}

public class WaitForSecondsRealtime : CustomYieldInstruction
{
    private float waitTime;

    public override bool keepWaiting
    {
        get
        {
            return Time.realtimeSinceStartup < waitTime;
        }
    }

    public WaitForSecondsRealtime(float time)
    {
        waitTime = Time.realtimeSinceStartup + time;
    }
}

}

The problem has nothing to do with “WaitForSecondsRealtime”. The problem are those two lines:

StartCoroutine(Pause(5f));
SceneManager.LoadScene("NextScene");

Those two lines will run right after each other. So first you start your coroutine “Pause” and at the same time your load “NextScene” which will destroy your gameobject where your coroutine runs on.

As you should know you can’t “delay” or pause inside Update. You can only “wait” inside a coroutine. If you want to delay the LoadScene call you have to place it inside the coroutine.

If your intention is to switch the scene immediately but keep the coroutine running you have to use DontDestroyOnLoad on the gameobject that runs your coroutine so it survives the level load.