c# - 如何在 C#/Unity 中等待一段时间而不冻结代码?
问题描述
我正在制作一个练习游戏,以习惯在必须射鸟的地方编码。当子弹用完时,您需要按“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;
}
}
推荐阅读
- mongodb - MongoDB mongod 未运行
- c# - 使用 Microsoft Graph 创建新日历
- c++ - C++ boost::asio::ip::tcp::acceptor 有时不接受连接器?
- c++ - 错误:无法解析对重载函数的引用;你的意思是叫它吗?
- magento - Stripe Payment - 卸载噩梦
- dart - Dart - 获取列表中的总金额
- javascript - 递归地从json中查找依赖项
- php - 数组项计数
- xml - 如何从 \Yii::$app->request 中检索 XML 数据?
- javascript - 什么时候调用自定义 React Hooks?