我正在制作一个练习游戏,以习惯在必须射杀鸟的地方进行编码。当子弹用完时,需要按"r"键重新装入子弹。我希望在按下按钮和子弹重新加载之间有一个延迟,但到目前为止,我发现的是冻结所有东西的代码(如下所示(。有没有办法防止代码冻结所有内容?摘要:当按下"r"按钮时,下面的代码会冻结所有内容(整个游戏(。有没有我可以使用的代码不会冻结所有内容,并且只需等待2秒钟就可以运行下一个操作?
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
}
}
(我知道这是一个公认的答案,我只是觉得这种方法会更好(