Unity yield return new WaitForSeconds(2f); doesn't work

Viewed 208

I have made a script allowing to go up the value of the player's stamina after 2 seconds. My code works perfectly without the WaitForSeconds, but suddenly the rise of the stamina is done instantly and that's not what I want. So I added the WaitForSeconds but nothing helps, it doesn't work.

        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;
        }

Thank you in advance for the help you will provide me.

1 Answers

Presuming this code is run in an update loop, you're currently cancelling the coroutine every frame while not running.

Ie. if shift, lose stamina, else, cancel regen, and start regen

I presume you're after something more like this:

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. if shift, cancel regen and lose stamina, else, start regen (if not already started)

Related