這個問題在這里已經有了答案: 如何使腳本以簡單的方式統一等待/休眠 6 個答案 昨天關門。
所以我正在嘗試使用此代碼:
GetComponent<Renderer>().material.color = Color.red;
Thread.Sleep(500);
GetComponent<Renderer>().material.color = Color.white;
但是當我這樣做時,什么也沒有發生;看來,如果我添加一個 debug.log(),即使 debug.log 在 thread.sleep 之前,它也會在 500 毫秒后列印它,這也會發生在 task.delay() 中。
但是,如果我洗掉 Thread.Sleep 或延遲一切正常作業,顏色會發生變化,可以確認它在使用 debug.log 時會發生變化。
那么 task.delay 或 thread.sleep 是什么導致它附近的代碼無法運行呢?或者,在運行以下代碼行之前是否有更有效的方法來生成等待?
uj5u.com熱心網友回復:
您應該統一使用WaitForSeconds,而不是 Thread.Sleep。如果你要讓主執行緒休眠,你的整個游戲就會凍結。 在這里閱讀更多
您將需要創建一個協程。
public IEnumerator ChangeMaterialColorRoutine()
{
var mat = GetComponent<Renderer>().material;
mat.color = Color.red;
yield return new WaitForSeconds(0.5f);
mat.color = Color.white;
}
然后你使用StartCoroutine啟動協程
StartCoroutine(
ChangeMaterialColorRoutine()
);
或者,您可以在更新中添加一個“計時器”,將其添加到每個幀,直到達到/超過所需的持續時間。
private float waitTimer = 0;
private float timeToWait = 0.5f; // unit: seconds
private bool isWaitingForTimer = false;
void Update()
{
if (isWaitingForTimer)
{
waitTimer = Time.deltaTime; // add how much time passed since last frame
if (waitTimer >= timeToWait)
{
waitTimer = 0;
isWaitingForTimer = false;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432319.html
上一篇:如何與transform.Rotate保持一致的旋轉速度?
下一篇:如何僅在x上移動?
