Unity time countdown function - coroutine

StopCoroutine(countdownCoroutine); Stopping the coroutine can only stop the current process, and the coroutine will be restarted when it starts next time. So if you want to really stop, you need to use the variable bool value to judge.

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

public class StarContTest : MonoBehaviour
{
    
    
    public Button StopBtn;
    public Button StartBtn;
    public int currentTime;
    public Text countdownText;
    public Slider progressBar;
    public float TotalTime {
    
     get; set; }
    public float CurrentTime {
    
     get; set; }
    private bool isCountdownRunning = true;
    private Coroutine countdownCoroutine;

    // Start is called before the first frame update
    void Start()
    {
    
    
        TotalTime = 10f;
        CurrentTime = TotalTime;
        countdownCoroutine = StartCoroutine(StartCountdown());
        StopBtn.onClick.AddListener(StopCountdownButtonClicked);
        StartBtn.onClick.AddListener(StartCountdownButtonClicked);
    }

    private void StopCountdownButtonClicked()
    {
    
    
        if (countdownCoroutine != null)
        {
    
    
            StopCoroutine(countdownCoroutine);
            countdownCoroutine = null;
            isCountdownRunning = false;
        }
    }

    private void StartCountdownButtonClicked()
    {
    
    
        if (!isCountdownRunning)
        {
    
    
            CurrentTime = TotalTime;
            countdownCoroutine = StartCoroutine(StartCountdown());
            isCountdownRunning = true;
        }
    }

    private void UpdateProgressBar()
    {
    
    
        progressBar.maxValue = TotalTime;
        progressBar.value = CurrentTime;
    }

    public void UpdateCountdownText()
    {
    
    
        countdownText.text = CurrentTime.ToString("F0") + "s";
    }

    public void DecreaseTime()
    {
    
    
        CurrentTime--;
    }

    private IEnumerator StartCountdown()
    {
    
    
        while (CurrentTime > 0f)
        {
    
    
            yield return new WaitForSeconds(1f);
            DecreaseTime();
            UpdateCountdownText();
            UpdateProgressBar();
        }

        if (!isCountdownRunning)
        {
    
    
            // 执行停止操作
            // 可以在这里添加你需要的代码
        }
        else
        {
    
    
            // 倒计时结束后的操作
            countdownText.text = "0";
            // 可以在这里添加你需要的代码
        }
    }

    // Update is called once per frame
    void Update()
    {
    
    

    }
}

Guess you like

Origin blog.csdn.net/weixin_44047050/article/details/131576233