在unity3d中运行时结束协程

我试图用按钮启动和结束协程。我可以启动协程,但无法停止,如果在第一次启动协程后再次单击该按钮,它将再次重新启动并且滑块值会上升。


这是我的代码


    public void LoopButton(){


    if (lb == 1){

        StopCoroutine (AutoLoop());

        tb--;

    } else {

        StartCoroutine (AutoLoop ());

        tb++;

    }

}


IEnumerator AutoLoop(){


    slider.value = slider.minValue;


    while(slider.value < slider.maxValue){

        slider.value++;

        yield return new WaitForSeconds(0.5f);

    }


    StartCoroutine (AutoLoop());

}


达令说
浏览 503回答 3
3回答

慕仙森

您需要使用调用由所返回StopCoroutine的相同 引用来进行调用,如下所示:CoroutineStartCoroutineprivate Coroutine loopCoroutine;public void LoopButton(){&nbsp; &nbsp; if (lb == 1)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; StopCoroutine(loopCoroutine);&nbsp; &nbsp; &nbsp; &nbsp; tb--;&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; loopCoroutine = StartCoroutine(AutoLoop());&nbsp; &nbsp; &nbsp; &nbsp; tb++;&nbsp; &nbsp; }}要使用此方法,请将您的AutoLoop方法更改为使用while循环,而不是AutoLoop在方法结束时启动另一个协程。否则,您将无法停止从末尾开始的新协程AutoLoop。IEnumerator AutoLoop(){&nbsp; &nbsp; while(true)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; slider.value = slider.minValue;&nbsp; &nbsp; &nbsp; &nbsp; while (slider.value < slider.maxValue)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; slider.value++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield return new WaitForSeconds(0.5f);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}对于另一个解决方案,正如另一个用户所评论的那样,也可以通过布尔标志来停止协程:private bool stopLoop;public void LoopButton(){&nbsp; &nbsp; if (lb == 1)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; stopLoop = true;&nbsp; &nbsp; &nbsp; &nbsp; tb--;&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; stopLoop = false;&nbsp; &nbsp; &nbsp; &nbsp; StartCoroutine (AutoLoop ());&nbsp; &nbsp; &nbsp; &nbsp; tb++;&nbsp; &nbsp; }}IEnumerator AutoLoop(){&nbsp; &nbsp; slider.value = slider.minValue;&nbsp; &nbsp; while (slider.value < slider.maxValue && !stopLoop)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; slider.value++;&nbsp; &nbsp; &nbsp; &nbsp; yield return new WaitForSeconds(0.5f);&nbsp; &nbsp; }&nbsp; &nbsp; if (!stopLoop)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; StartCoroutine(AutoLoop());&nbsp; &nbsp; }}但是,StopCoroutine为了提高可读性和整洁度,使用Unity优于使用布尔值标志。

呼啦一阵风

使用字符串作为协程名称。像这样:public void LoopButton(){&nbsp; &nbsp; if (lb == 1){&nbsp; &nbsp; &nbsp; &nbsp; StopCoroutine ("AutoLoop");&nbsp; &nbsp; &nbsp; &nbsp; tb--;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; StartCoroutine ("AutoLoop");&nbsp; &nbsp; &nbsp; &nbsp; tb++;&nbsp; &nbsp; }}IEnumerator AutoLoop(){&nbsp; &nbsp; slider.value = slider.minValue;&nbsp; &nbsp; while(slider.value < slider.maxValue){&nbsp; &nbsp; &nbsp; &nbsp; slider.value++;&nbsp; &nbsp; &nbsp; &nbsp; yield return new WaitForSeconds(0.5f);&nbsp; &nbsp; }&nbsp; &nbsp; StartCoroutine ("AutoLoop");}

www说

您可以使用StopCoroutine。此处的更多信息:https&nbsp;:&nbsp;//docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html
打开App,查看更多内容
随时随地看视频慕课网APP