在 unity3d 中 运行 时结束协程

Ending a coroutine while running in 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());
}

您可以使用 StopCoroutine.

更多信息在这里: https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html

协程名称使用字符串。像这样:

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

您需要调用 StopCoroutine 并引用 StartCoroutine 返回的 same Coroutine,如下所示:

private Coroutine loopCoroutine;

public void LoopButton()
{
    if (lb == 1)
    {
        StopCoroutine(loopCoroutine);
        tb--;
    }
    else
    {
        loopCoroutine = StartCoroutine(AutoLoop());
        tb++;
    }
}

要使用此方法,请将您的 AutoLoop 方法更改为使用 while 循环,而不是在方法末尾启动另一个 AutoLoop 协程。否则,您将无法停止这个在 AutoLoop.

结束时启动的新协程
IEnumerator AutoLoop()
{
    while(true)
    {
        slider.value = slider.minValue;

        while (slider.value < slider.maxValue)
        {
            slider.value++;
            yield return new WaitForSeconds(0.5f);
        }
    }
}

对于替代解决方案,正如另一位用户评论的那样,也可以通过布尔标志停止协程:

private bool stopLoop;

public void LoopButton()
{
    if (lb == 1)
    {
        stopLoop = true;
        tb--;
    }
    else
    {
        stopLoop = false;
        StartCoroutine (AutoLoop ());
        tb++;
    }
}

IEnumerator AutoLoop()
{
    slider.value = slider.minValue;

    while (slider.value < slider.maxValue && !stopLoop)
    {
        slider.value++;
        yield return new WaitForSeconds(0.5f);
    }

    if (!stopLoop)
    {
        StartCoroutine(AutoLoop());
    }
}

但是,使用 Unity 的 StopCoroutine 比使用布尔标志更可读性和简洁性。