unity3d - unity yield return new WaitForSeconds(2f); 不工作
问题描述
我制作了一个脚本,允许在 2 秒后提高玩家的耐力值。我的代码在没有 WaitForSeconds 的情况下可以完美运行,但是突然间耐力的提升会立即完成,这不是我想要的。所以我添加了 WaitForSeconds 但没有任何帮助,它不起作用。
if (Input.GetKey(KeyCode.LeftShift))
{
currentstamina -= 1f;
if(currentstamina <= 0)
{
currentstamina = 0;
runningSpeed = walkingSpeed;
}
}
else if (Input.GetKey(KeyCode.LeftShift) == false)
{
if (currentstamina < 20)
{
if (regen != null)
StopCoroutine(regen);
regen = StartCoroutine(StaminaBack());
}
}
IEnumerator StaminaBack()
{
yield return new WaitForSeconds(2f);
while(currentstamina < startingstamina)
{
currentstamina += startingstamina / 100;
yield return regenTick;
}
regen = null;
}
预先感谢您为我提供的帮助。
解决方案
假设此代码在更新循环中运行,您当前在不运行时每帧取消协程。
IE。if shift, 失去体力, else, 取消regen, 开始regen
我想你正在追求更多这样的东西:
if (Input.GetKeyDown(KeyCode.LeftShift))
{
if (regen != null)
{
StopCoroutine(regen);
regen = null;
}
currentStamina -= 1f;
if (currentstamina <= 0)
{
currentstamina = 0;
runningSpeed = walkingSpeed;
}
}
else if (regen == null && stamina < 20)
{
regen = StartCoroutine(StaminaBack());
}
IE。如果轮班,取消再生并失去耐力,否则,开始再生(如果尚未开始)
推荐阅读
- nginx - NGINX 充当正向代理?
- amazon-web-services - terraform aws_lb_listener_rule 条件争论未在 terraform 0.12.20 中得到认可
- html - 媒体查询不适用
- python - 将“Python 模板字符串”扩展为非 ASCII
- android - android - 访问相机强制关闭 api 29
- linux - QtCreator 找不到 emscripten 编译器
- azure - 将应用从一个 Azure 目录注册到另一个 Azure 订阅
- assembly - x86 程序集 - 从 dword 到 qword 的 mov 和 movzx?
- html - 如何在jinja2模板中使用if语句
- typescript - 在编写 TypeScript 转换时,`setTextRange` 做什么以及何时需要?