How to stop co-routine?

社会主义新天地 提交于 2019-11-28 08:16:22

问题


When two co-routines are running, how do you stop the first co-routine?

GLOBALS.stableTime = 5;

IEnumerator StableWaittingTime ()
{
        yield return new WaitForSeconds (1f);
        if (GLOBALS.stableTime == 0) {
                GameManager.instance.LevelFaildMethod ();
        } else {
                GameManager.instance.stableWaittingTime.text = GLOBALS.stableTime.ToString ();
                GLOBALS.stableTime--;
                StartCoroutine ("StableWaittingTime");
        }
}

回答1:


@Imapler answer is almost all you need. I would just add that StopCoroutine method of MonoBehaviour is overloaded and has 3 types of parameters, so it is possible to stop many coroutines of same name. For your need here, just use yield break; like this:

void Start () 
{
    StartCoroutine (StableWaittingTime ());
}

IEnumerator StableWaittingTime ()
{
    yield return new WaitForSeconds (1f);
    if (false) 
    {
        // do something
    } 
    else 
    {
        // do something
        StartCoroutine (StableWaittingTime ());
        yield break;
    }
}



回答2:


There are three ways to stop coroutines. First is to call StopAllCoroutines. The second is to call StopCoroutine. And the third is to do a yeild break from within the coroutine.

StopAllCoroutines stop all coroutines, StopCoroutine stop all coroutines with a give name and yeild break stops that coroutine. Worth noting is that both StopAllCoroutines and StopCoroutine can only stop a coroutine when the coroutine reaches a yield return.

So if you have two coroutines with the same name and you want to stop the one you are executing in you do yeild break. Interestingly, if you want to stop every other coroutine than the one you are executing in you call StopCoroutine from within that coroutine.



来源:https://stackoverflow.com/questions/25204035/how-to-stop-co-routine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!