Question about Stopping a Coroutine

Hello everyone,

Note I used different variable/function names from Rick’s examples

In the video, I noticed we can start a Coroutine with:
StartCorotuine(ShootContinuously());

However, to stop the Coroutine, we needed to create a variable as a handle to stop the Coroutine:

    if (Input.GetButtonDown("Fire1"))
    {
        shootingCoroutine = StartCoroutine(ShootContinuously());
    }
    if (Input.GetButtonUp("Fire1"))
    {
        StopCoroutine(shootingCoroutine);

I understand why you wouldn’t use StopAllCoroutines, but I’m curious why we couldn’t use:
StopCoroutine(ShootContinuously);

Thanks!

2 Likes

I don’t have your answer but I’m interested what it is when you get one, heck I don’t think I’ve even seen that lecture, but you say Rick and 2D, so I guess this is in the remastered material… I should go back and try it out.

1 Like

I think they originally had that but someone pointed out that it was bad practice and could cause issues.

What if you did it five times?

StartCoroutine(FireContinuously());
StartCoroutine(FireContinuously());
StartCoroutine(FireContinuously());
StartCoroutine(FireContinuously());
StartCoroutine(FireContinuously());

And then you wanted to stop one of them. How would you do it? Unity/C# hates ambiguity. If you tell it to stop something, it wants to know exactly what instance to stop.

So the idea is if you plan to stop it later, storing the coroutine in a variable will give you a precise reference to tell the system exactly which coroutine should be stopped - even if you only have one.

I’m actually really pleased that they updated the course with this change. What if the coroutine was something like UpdatePlayerUI(player)? Then you’d definitely want to know how to stop a particular coroutine instead of just some random one.

4 Likes

I actually tried it that way originally and for me it just didn’t work at all, but it worked fine once I changed to the variable way that Rick used.

I came on to ask the same question, still not sure why it wouldn’t work that way but as Anthony has pointed out it seems much better practice to do it the way Rick has stated.

I had no idea you could have multiple instances of a coroutine running simultaneously. That’s actually a very good reason to store it in a variable and makes more sense of the line:

"firingCoroutine = StartCoroutine(“FireContinuously:);”

I thought it was storing the coroutine but it seems it’s storing an instance of the coroutine.

Thanks for the explanation!

Privacy & Terms