【问题标题】:Unity yield return new WaitForSeconds(2f); doesn't workunity yield return new WaitForSeconds(2f);不工作
【发布时间】:2021-07-18 21:28:02
【问题描述】:

我制作了一个脚本,允许在 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


    【解决方案1】:

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

    即。 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());
    }
    

    即。如果轮班,则取消再生并失去耐力,否则,开始再生(如果尚未开始)

    【讨论】:

      猜你喜欢
      • 2019-06-19
      • 2018-11-09
      • 2016-06-15
      • 2012-10-14
      • 1970-01-01
      • 2015-06-14
      • 2015-03-02
      • 2017-12-08
      • 2018-12-18
      相关资源
      最近更新 更多