Ben Rubin
Ben Rubin

Reputation: 7341

Coroutine being execute twice after starting, stopping, starting again

I have a coroutine that I'm using to animate a cursor. The coroutine looks like this

private IEnumerator AnimateCursor(Vector2 targetScreenPoint)
{
   while (true)
   {
      // Do animation stuff          

      Debug.Log(targetScreenPoint.ToString());
      yield return null;
   }
}

Everything works fine the first time I start the coroutine. If the cursor moves, I call StopCoroutine("AnimateCursor") to stop the coroutine, and then start the coroutine again with a new value for the targetScreenPoint parameter.

When I start the coroutine again, the animated cursor still gets drawn in its original position and the Debug.Log prints both the first and second values of targetScreenPoint (which is why I think the coroutine is executing twice during each update loop).

If I replace StopCoroutine("AnimateCursor") with StopAllCoroutines(), it works correctly and the second time the coroutine starts, it only prints the second value of targetScreenPoint.

Does anyone know what's going on?

EDIT: I was wrong about the cursor still animating while the debugger is running. I think the problem is with my StopCoroutine, but I don't know why. Is there a special way that I have to stop a coroutine if the coroutine takes parameters?

Upvotes: 3

Views: 1880

Answers (2)

DietChugg
DietChugg

Reputation: 24

The selected as "correct" answer is incorrect. StartCoroutine returns type Coroutine which StopCoroutine can accept as an alternate overload to stop a Coroutine.

In example:

/// <summary>
    /// Not that it makes any sense to start a Coroutine just to stop it...
    /// </summary>
    public void StartAndThenImmediatlyStopCoroutine()
    {
        Coroutine coroutine = StartCoroutine(MyCoroutine());
        StopCoroutine(coroutine);
        Coroutine anotherCoroutineExample = StartCoroutine("MyCoroutine");//Ewww... String based co-routine starting. This breaks Find All References in Visual Studios so you can't actually know where it's being called.
        StopCoroutine(anotherCoroutineExample);
        Coroutine evenMoreCoroutine = StartCoroutine(MyCoroutineWithParamaters(1, 2.2f, "Paramater Routines Rock!!!"));
        StopCoroutine(evenMoreCoroutine);
    }

    public IEnumerator MyCoroutine()
    {
        yield return new WaitForSeconds(1.0f);
    }

    public IEnumerator MyCoroutineWithParamaters(int myNumber, float myFloat, string myString)
    {
        yield return new WaitForSeconds(1.0f);
    }

Upvotes: -1

Harry
Harry

Reputation: 5707

You need to use StartCoroutine("AnimateCursor", targetScreenPoint); - string variance.

Because StopCoroutine("AnimateCursor") only works if you use that string variance.

If you use StartCoroutine(AnimateCursor(targetScreenPoint)); - IEnumerator variance - then there is no way you can stop your coroutine.

Upvotes: 2

Related Questions