本文介绍了如何停止协程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当两个协程正在运行时,如何停止第一个协程?

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");
        }
}

推荐答案

@Imapler 答案几乎就是您所需要的.我只想补充一下 MonoBehaviourStopCoroutine 方法是重载的,并且有 3 种类型的参数,因此可以停止许多同名的协程.根据您的需要,只需使用屈服中断;像这样:

@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;
    }
}

这篇关于如何停止协程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 08:04