TheWhiteRice2006
TheWhiteRice2006

Reputation: 21

How can I get the remaining time left on a Unity coroutine?

Hi I am wondering how I could get the remaining time on a running coroutine. I want to run another coroutine off the remaining other coroutine. Sorta like this:

void test (){
    StartCoroutine(TestOne());
    if(Input.GetKey(KeyCode.A)){        // some way to get remaining time, or 
        StartCoroutine(TestTwo(time));  // something like this: 
                                        // float time = TestOne.GetRemainingTime();      
    }   
}

Upvotes: 1

Views: 2175

Answers (2)

Daniel
Daniel

Reputation: 7714

Make test a IEnumerator:

IEnumerator test (){

    yield return StartCoroutine(TestOne());  //wait until TestOne() is over 

    yield return new WaitUntil(() => Input.GetKey(KeyCode.A)); //wait until user press A

    yield return StartCoroutine(TestTwo(time));  //wait until TestTwo(time) is over

}   

The last line could be only StartCoroutine(TestTwo(time)); if you don't need the code to wait anything else.

This way, you don't need to know the remaining time, you just wait until it ends and then run everything else.

Upvotes: 0

Marco Elizondo
Marco Elizondo

Reputation: 562

It depends a lot on what you are trying to do, but there is not a .GetRemainingTime() method in Unity.

A general solution is having a counter in your couroutine, something like...

float remainingTimeA = 0f;

IEnumerator MyRoutineA()
{
    float duration = 2.0f //Two seconds

    remainingTimeA = duration; //Set the remaining time as the duration
    while(remainingTimeA > 0f) //While there is still time
    {
        remainingTimeA -= Time.deltaTime; //Reduce the timer with time between previous and actual frame
        yield return null; //Wait for this frame to end
    }
}

What you can do is having a remainingTimeA variable that you can check if you need it. You initialize it on the coroutine with the duration you want to wait. And then use a while to manually create the waiting each frame.

yield return null waits for the end of the frame, instead of new WaitForSeconds(duration) you are just wainting each frame while you reduced your timer by Time.deltaTime that is the time between each frame. So if 1 second have passed since the start of the coroutine, remainingTimeA should be 1.0f.

I hope is clear.

Upvotes: 4

Related Questions