[英]How can I cancel/stop the coroutine and also to pause the coroutine?
為了啟動和停止/取消協程,我使用了 startTimer bool 標志,但它不起作用。 當我運行游戲並檢查 startTimer 的標志時,計時器開始,但是當我取消選中標志 startTimer 時,計時器永遠不會停止,當我再次檢查 startTimer nothingchange 時,計時器會定期倒計時。
pauseTimer 我也不知道該怎么做。 我希望當 pauseTimer 為 true 時,協程將在它所在的位置暫停,而當 pauseTimer 為 false 未選中時,協程應該從最后一個暫停位置繼續。
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;
}
}
}
根據您的代碼,這是停止/暫停計時器的方法
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);
}
供參考,
人們過去常常在Update()中使用Time.deltaTime來實現定時器
public float timer = 100f;
private void Update()
{
if (!pauseTimer)
{
timer -= Time.deltaTime;
countdownDisplay.text = timer.ToString("0.0");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.