解決了我找錯地方了。我可以看到 gameOver 變為 true 但其他代碼使它在 Coroutine 停止之前變回 false ...
我有一個協程,我無法停止。這顯然聽起來像重復,可能是一個簡單的解決方案,但我已經閱讀了很多示例、檔案和其他人的問題,現在我快瘋了。有人可以告訴我我做錯了什么嗎?我在代碼中嘗試了許多不同的選項,例如:啟動/停止時不快取 CR。使用名稱字串啟動/停止 CR。我嘗試在 while 回圈中使用“true”,然后使用其他方式(如果條件,其他布林值)。
一切都在同一個檔案中的同一個 MonoBehaviour 中。我看到 gameOver 在日志中設定為 true。(將 gameOver 更改為 true 的代碼不在下面的片段中)
Move() 應該從 gameOver 變為 true 和停止 CR 時停止執行,對嗎?
private float moveDelay = 0.4f;
private bool gameOver = false;
void Start() {
StartCoroutine(Mover());
}
void Update()
{
if (gameOver)
{
StopCoroutine(Mover());
StopAllCoroutines;
}
}
private IEnumerator Mover()
{
while (!gameOver)
{
Move();
yield return new WaitForSeconds(moveDelay);
}
}
uj5u.com熱心網友回復:
將它放在一個變數中以停止單個協程。如果您使用的是 StopAllCoroutines,請使用 呼叫它(),如下所示:StopAllCoroutines();
private float moveDelay = 0.4f;
private bool gameOver = false;
private IEnumerator myCoroutine;
void Start() {
myCoroutine = Mover();
StartCoroutine(myCoroutine);
}
void Update()
{
if (gameOver)
{
StopCoroutine(myCoroutine);
//StopAllCoroutines();
}
}
private IEnumerator Mover()
{
while (!gameOver)
{
Move();
yield return new WaitForSeconds(moveDelay);
}
}
uj5u.com熱心網友回復:
像這樣修復它:
private float moveDelay = 0.4f;
private bool gameOver = false;
private Coroutine _coroutine;
void Start() {
_coroutine = StartCoroutine(Mover());
}
void Update()
{
if (gameOver)
{
StopCoroutine(_coroutine);
}
}
private IEnumerator Mover()
{
while (!gameOver)
{
Move();
yield return new WaitForSeconds(moveDelay);
}
}
uj5u.com熱心網友回復:
獲得相同效果的一種更簡單的方法是InvokeRepeating在您的 start 方法中使用,然后gameOver在滿足您的條件后停止它,如下所示:
private float moveDelay = 0.4f;
private bool gameOver = false;
void Start()
{
InvokeRepeating("Move",0,moveDelay); //Function to run, Start Delay, Repeat delay
}
void Update()
{
if (gameOver)
{
CancelInvoke(); //Note: you can specify a single invoke to cancel or leave it blank to cancel all invokes
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/359809.html
下一篇:使用動態添加的過濾器過濾串列
