為了啟動和停止/取消協程,我使用了 startTimer bool 標志,但它不起作用。當我運行游戲并檢查 startTimer 的標志時,計時器開始但當我取消選中標志 startTimer 時,計時器永遠不會停止,當我再次檢查 startTimer 時,計時器沒有變化,計時器會定期倒計時。
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;
}
}
}
uj5u.com熱心網友回復:
根據您的代碼,這是停止/暫停計時器的方法
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");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/403887.html
標籤:
上一篇:物體錯誤地與跟蹤EFCore分離
下一篇:.NET控制器中的兩個建構式
