首页 > 解决方案 > 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;
        }

预先感谢您为我提供的帮助。

标签: unity3d

解决方案


假设此代码在更新循环中运行,您当前在不运行时每帧取消协程。

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。如果轮班,取消再生并失去耐力,否则,开始再生(如果尚未开始)


推荐阅读