I can't stop my coroutine.

I have this coroutine:

private IEnumerator CountDownToStartGame()
{
    yield return new WaitForSeconds(countdownToStartGame); //Lasts 10 seconds

    StartCoroutine(StartGame());
}

I start it like this: countdownCoroutine = StartCoroutine(CountDownToStartGame());

If something happens, I call this method:

public void StopStartingGame()
{
    StopCoroutine(countdownCoroutine);

    Debug.Log("Coroutine stopped");
}

But its not working, how can I stop it?

Coroutines are NOT always an appropriate solution: know when to use them!

Generally, if your design requires you to call StopCoroutine(), then don’t make it a coroutine.

It sounds like you really need something like a cooldown timer, and you want to interrupt it.

This means a timer that without further intervention will cause something to happen in X seconds.

But… things can happen that extend that time (or stop the count entirely), usually by resetting the timer.

Cooldown timers, gun bullet intervals, shot spacing, rate of fire:

I’m making a multiplayer game and when I client joins while the game is starting, I stop the countdown coroutine. I want it like that to avoid errors and to let the new player vote for the map and game-modes. Should I not use a coroutine?

I wouldn’t. Once start is pressed, set a timer to 10 seconds and count it down.

When players join, either stop the count or reset the count to 10 seconds.

There’s just not a lot of ways this code can go bad:

// zero means don't start, nonzero means start in that amount of time.
float timeToStart;

void Update()
{
  if (timeToStart > 0)
  {
    timeToStart -= Time.deltaTime;
    if (timeToStart <= 0)
    {
       // call the start game here
    }
  }
}

void ResetCountdown()
{
  timeToStart = 10;
}

void StopCountdown()
{
  timeToStart = 0;
}
1 Like