Daniel Lip
Daniel Lip

Reputation: 11317

How can I cancel/stop the coroutine and also to pause the coroutine?

For starting and stopping/cancelling the coroutine I'm using the startTimer bool flag but it's not working. When I'm running the game and check the flag of startTimer the timer start but when I uncheck the flag startTimer the timer never stop and when I check again the startTimer nothingchange the timer is keep counting back regular.

The pauseTimer I'm not sure how to do it either. I want that when pauseTimer is true the coroutine will pause at where it is and when pauseTimer is false unchecked the coroutine should continue from last pause place.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CountdownController : MonoBehaviour
{
    public int countdownTime;
    public Text countdownDisplay;
    public bool startTimer = false;
    public bool pauseTimer = false;

    private bool startOnce = true;

    private void Start()
    {
        if (startTimer)
        {
            StartCoroutine(CountdownToStart());
        }
    }

    private void Update()
    {
        if(startTimer)
        {
            StartTimer();
        }
        else
        {
            StopCoroutine(CountdownToStart());
        }
    }

    private IEnumerator CountdownToStart()
    {
        while(countdownTime > 0)
        {
            countdownDisplay.text = countdownTime.ToString();

            yield return new WaitForSeconds(1f);

            countdownTime--;
        }

        countdownDisplay.text = "GO!";

        yield return new WaitForSeconds(1f);

        countdownDisplay.gameObject.SetActive(false);
    }

    public void StartTimer()
    {
        if (startOnce)
        {
            StartCoroutine(CountdownToStart());

            startOnce = false;
        }
    }
}

Upvotes: 0

Views: 516

Answers (1)

siusiulala
siusiulala

Reputation: 1060

Base on your code, here is how to stop/pause your timer

private IEnumerator CountdownToStart()
{
    while (countdownTime > 0)
    {
        // Use break to stop coroutine
        if (!startTimer)
            yield break;

        // Use continue to pause coroutine
        if (pauseTimer)
        {
            // wait a while before continue to avoid infinite loop
            yield return new WaitForEndOfFrame();
            continue;
        }
            
        countdownDisplay.text = countdownTime.ToString();
        yield return new WaitForSeconds(1f);
        countdownTime--;
    }

    countdownDisplay.text = "GO!";

    yield return new WaitForSeconds(1f);

    countdownDisplay.gameObject.SetActive(false);
}

Fyi,

People used to implement timer with Time.deltaTime in Update()

public float timer = 100f;
private void Update()
{
    if (!pauseTimer)
    {
        timer -= Time.deltaTime;
        countdownDisplay.text = timer.ToString("0.0");
    }
}

Upvotes: 1

Related Questions