我最近在 C# unity 中學習了協程,并嘗試創建一個等待函式來在代碼之間等待。它同時列印兩個陳述句,而不是等待三秒鐘。有誰知道這個問題的解決方案?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Learninghowtoprogram : MonoBehaviour
{
private void Start()
{
print("hello");
wait(3);
print("hello2");
}
IEnumerator waito(float time)
{
yield return new WaitForSeconds(time);
}
void wait(float time)
{
StartCoroutine(waito(time));
}
}
uj5u.com熱心網友回復:
這里的問題是當Start()被呼叫時它會嘗試逐行執行
print("hello");
wait(3);
print("hello2");
因此,當您呼叫wait(3)它時,它會進入它自己的范圍并呼叫waito協程。
現在看到yield return new WaitForSeconds(time);它正在正確地完成它的作業,這意味著它正在等待 3 秒,但是在它的范圍內(在它自身內部),所以你可以做的就是像這樣移動print("hello");并print("hello2");在協程本身中......
public class Learninghowtoprogram : MonoBehaviour
{
private void Start()
{
wait(3);
}
void wait(float time)
{
StartCoroutine(waito(time));
}
IEnumerator waito(float time)
{
print("hello");
yield return new WaitForSeconds(time);
print("hello2");
}
}
或者,您也可以wait()像這樣洗掉并直接啟動協程
public class Learninghowtoprogram : MonoBehaviour
{
private void Start()
{
StartCoroutine(waito(3));
}
IEnumerator waito(float time)
{
print("hello");
yield return new WaitForSeconds(time);
print("hello2");
}
}
uj5u.com熱心網友回復:
你可以試試下面的代碼,希望對你有幫助。
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
void Start()
{
print("hello");
StartCoroutine(WaitAndPrint(2.0F));
print("hello2");
}
IEnumerator WaitAndPrint(float waitTime)
{
yield return new WaitForSeconds(waitTime);
}
}
在協程開始和結束之前呼叫下一步。
private void Start()
{
StartCoroutine("DelayFunc");
}
IEnumerator DelayFunc()
{
print("hello");
yield return new WaitForSeconds(2);
print("hello2");
}
uj5u.com熱心網友回復:
如果您在功能中停止時間或等待執行任務。使用
但我認為這是糟糕的設計。Awake被稱為之前Start,Start被稱為之前的第一個Update。有時 Unity 開發人員依賴該順序來訪問參考等。通過延遲執行,Start您會稍微改變該順序。
因此,雖然上述方法有效,但我建議檢查一個計時器變數Update或在 Start 中啟動一個單獨的協程,稍后運行,但仍然讓Startreturn void。
uj5u.com熱心網友回復:
在 start 方法中,如果您嘗試呼叫 void 'wait',請不要在括號中輸入 3。您可能還想將 'Void wait ()' 移動到 'waitto' 上方,像這樣......`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Learninghowtoprogram : MonoBehaviour
{
private void Start()
{
print("hello");
wait();
print("hello2");
}
void wait(float time)
{
StartCoroutine(waito(time));
}
IEnumerator waito(float time)
{
yield return new WaitForSeconds(time);
}
}`
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/491129.html
下一篇:粒子系統統一并不總是顯示,統一
