[英]How to wait a certain amount of time without freezing code in C#/Unity?
我正在制作一個練習游戲,以習慣在必須射鳥的地方進行編碼。 當子彈用完時,您需要按“r”鍵重新加載子彈。 我希望在按下按鈕和子彈重新加載之間有一個延遲,但到目前為止我發現的是凍結所有內容的代碼(如下所示)。 有沒有辦法防止代碼凍結所有內容? 總結:當按下“r”按鈕時,下面的代碼會凍結所有內容(整個游戲)。 是否有我可以使用的代碼不會凍結所有內容並且在運行下一個操作之前只等待 2 秒?
IEnumerator TimerRoutine()
{
if (Input.GetKeyDown(KeyCode.R))
{
yield return new WaitForSeconds(2); //Fix this, freezes everything
activeBullets = 0;
}
}
使用 Coroutines 來設置這個延遲
if (Input.GetKeyDown(KeyCode.R) && isDelayDone) // defined isDelayDone as private bool = true;
{
// When you press the Key
isDelayDone = false;
StartCoroutine(Delay());
IEnumerator Delay()
{
yield return new WaitForSeconds(2);
isDelayDone = true;
activeBullets = 0;
}
}
您的問題是您在按鍵后等待 2 秒,但沒有等待實際的按鍵事件。
這是您的方法的修改版本,可以執行您想要的操作。
IEnumerator TimerRoutine()
{
while(activeBullets == 0) // Use the bullets value to check if its been reloaded
{
if (Input.GetKeyDown(KeyCode.R)) // Key event check each frame
{
// Key event fired so wait 2 seconds before reloading the bullets and exiting the Coroutine
yield return new WaitForSeconds(2);
activeBullets = reloadBulletsAmount;
break;
}
yield return null; // Use null for the time value so it waits each frame independant of how long it is
}
}
(我知道這有一個公認的答案,我只是覺得這種方法會更好)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.