Coroutine trouble (stop coroutine with a condition)

Hello All,

My problem is, that I have a simple coroutine eg. like this one:

    public IEnumerator Test()
    {
        while (???)
        {
            Debug.Log("coroutine");
            yield return null;
        }
    }

I have an update cycle as well:

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            StartCoroutine(Test());
        }
    }

So currently as you see it’s working, when I push the mousebutton down, the above coroutine will be started. But I’m in trouble because I would like to solve, that if I push the button down, the actually running coroutine should be stopped before running the coroutine again.

I know, that there is a stopcoroutine method in Unity, but I think, the concept of the coroutines is the conditions, and not the forced stop.

Thank you

Here are two ways:

  1. If this is the only coroutine for this MonoBehaviour, use StopAllCoroutines(). Example:
private void Update()
{
    if (Input.GetMouseButtonDown(0))
    { 
        StopAllCoroutines();
        StartCoroutine(Test());
    }
}

The downside is that this stops the coroutine immediately. If the coroutine needs to run some cleanup before exiting, you shouldn’t use this.

  1. Or use a flag. Here’s one suggestion:
private enum CoroutineState = { Inactive, Active, Reset };
private CoroutineState coroutineState = CoroutineState.Inactive;

private void Update()
{
    if (Input.GetMouseButtonDown(0))
    { 
        switch (coroutineState) {
        case CoroutineState.Inactive: StartCoroutine(Test());
        case CoroutineState.Active: coroutineState = CoroutineState.Reset; break;
        default: break;
        }
    }
}

public IEnumerator Test()
{
    coroutineState = CoroutineState.Active;
    while (???)
    {
        Debug.Log("coroutine");
        if (coroutineState == CoroutineState.Reset) 
        {
            StartCoroutine(Test());
            yield break;
        }
        yield return null;
    }
    coroutineState = CoroutineState.Inactive;
}

Don’t use StopCoroutine(). It only accepts a string, which means you have to invoke StartCoroutine with a string name (e.g., StartCoroutine(“Test”)), which is prone to typo bugs.

Thank you!

It’s working!

Happy to help!