- Home /
How to force Coroutine to finish
I want to force my coroutine to finish. This is code example. The log about Get out from Bus is never called, i think StopCoroutine didn't force to finish, but it removes the coroutine. What must I do to force the coroutine to finish?
// Use this for initialization
void Start () {
StartCoroutine ("Walking");
//Bus some how get accident
Debug.Log ("Bus getting Accident");
StopCoroutine ("UsingBus");
Debug.Log ("Bus getting Accident Done");
}
public IEnumerator Walking(){
yield return StartCoroutine ("UsingBus",5f);
Debug.Log ("Get out from Bus");
}
public IEnumerator UsingBus(float s){
Debug.Log ("Start Using Bus");
yield return new WaitForSeconds (s);
}
What do you mean when you say "force your coroutine to finish?"
When you call StopCoroutine, you prevent the "UsingBus" coroutine from finishing, which means "Walking" won't finish either. If you comment out that line, then everything will print out after 5 seconds.
What I mean is I want that the Walking Coroutine will stop waiting Using Bus Couroutine to finish.
I'm sorry, my English is not good.
StopCoroutine doesn't "finish" a coroutine. It's more like it "removes" it.
In any case, it seems like stopping a coroutine that another coroutine is dependent on causes it to not "yield return" so anything waiting for it won't hear back from it.
Is there a reason why you're structuring your code this way? Can't you do it another way with booleans or a state machine or something?
Answer by Jessespike · Sep 18, 2015 at 05:59 AM
Try something like this:
bool accidentOccured = false; // keeps track when accident has occured
// Use this for initialization
void Start()
{
StartCoroutine("Walking");
//Bus some how get accident
Debug.Log("Bus getting Accident");
//StopCoroutine("UsingBus");
accidentOccured = true; // accident occurs here
Debug.Log("Bus getting Accident Done");
}
public IEnumerator Walking()
{
yield return StartCoroutine("UsingBus", 5f);
Debug.Log("Get out from Bus");
}
public IEnumerator UsingBus(float s)
{
Debug.Log("Start Using Bus");
//yield return new WaitForSeconds(s);
float timePassed = 0f;
while(timePassed < s) // ride the bus for the given time
{
Debug.Log("Riding bus");
if (accidentOccured) // break from coroutine when accident occures
{
yield break;
}
yield return new WaitForEndOfFrame();
timePassed += Time.deltaTime;
}
}
Is there any good reason why you use WaitForEndOfFrame? It just creates unnecessary garbage, If you want a coroutine to loop each frame you should use
yield return null;
Take a look at this question over here. "WaitForEndOfFrame" is only needed in some rare special cases.
I didn't know there was a difference. Thanks for the tip!