如何在C#/Unity中等待一定时间而不冻结代码?
我正在做一个练习游戏,以习惯在你必须射击一只鸟的地方进行编码。子弹用完时,需要按“r”键重新装入子弹。我希望在按下按钮和子弹重新装弹之间有一个延迟,但到目前为止,我发现的是冻结一切的代码(如下所示)。有没有办法防止代码冻结所有内容? 小结:按下“r”按钮时,下面的代码会冻结所有内容(整个游戏)。是否有代码我可以使用,不会冻结一切,只需等待2秒,然后运行下一个操作如何在C#/Unity中等待一定时间而不冻结代码?,c#,unity3d,C#,Unity3d,我正在做一个练习游戏,以习惯在你必须射击一只鸟的地方进行编码。子弹用完时,需要按“r”键重新装入子弹。我希望在按下按钮和子弹重新装弹之间有一个延迟,但到目前为止,我发现的是冻结一切的代码(如下所示)。有没有办法防止代码冻结所有内容? 小结:按下“r”按钮时,下面的代码会冻结所有内容(整个游戏)。是否有代码我可以使用,不会冻结一切,只需等待2秒,然后运行下一个操作 IEnumerator TimerRoutine() { if (Input.GetKeyDown(K
IEnumerator TimerRoutine()
{
if (Input.GetKeyDown(KeyCode.R))
{
yield return new WaitForSeconds(2); //Fix this, freezes everything
activeBullets = 0;
}
}
使用协程设置此延迟
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
}
}
(我知道这是一个公认的答案,我只是觉得这种方法会更好)