"Resetting" WaitForSeconds

Hello all. This is my first post, and hopefully not my last! I have looked at the forum search results for similar topics, but I’m still scratching my head on this one.

Scenario: Player picks up a power up that increases fire rate for 5 seconds
Issue: If player picks up an additional power up, it does not “reset” the WaitForSeconds call
Desired resolution: If player picks up an additional power up before WaitForSeconds “ends”, WaitForSeconds is “reset” to the power up’s “bonusDuration”

Code:

IEnumerator FireRatePowerUp(float bonusSpeed, float bonusDuration)
    {
        if (lastPickUp == 0)
        {
            yield return new WaitForSeconds (bonusDuration);
        }
        else
        {
            lastPickUp = 0;
            fireRate = fireRate * bonusSpeed;
            yield return new WaitForSeconds (bonusDuration);
            fireRate = fireRate / bonusSpeed;
            lastPickUp = 1;
        }
}

I think I’m just not fully grasping coroutines or the limitations/implications of WaitForSeconds. Any help or suggestions would be greatly appreciated!

For a situation like this, I wouldn’t use a coroutine at all.

public float powerupLastsUntil = -1f;
public float bonusSpeed = 1f;
public float fireRate = 1f;

void Update() {
if (Time.time < powerupLastsUntil) {
fireRate = fireRate * bonusSpeed;
}
else {
fireRate = fireRate;
}
}

void FireRatePowerUp( float thisBonusSpeed, float bonusDuration) {
powerupLastsUntil = Time.time + bonusDuration;
bonusSpeed = thisBonusSpeed;
}
1 Like

Thanks for such a quick reply @StarManta ! Was trying something similar with a while loop earlier, but I’ll try out your suggestion now. Thanks again!

Hey @StarManta , if the if (Time.time < powerupLastsUntil) is in the Update method, it keeps returning true and ends up multiplying the fireRate by bonusSpeed once every frame. I tried putting it in the FireRatePowerUp method, but then fireRate is still unable to revert back to the original value.

Oh, right. There should be a baseFireRate that it uses in that instead.

void Update() {
if (Time.time < powerupLastsUntil) {
fireRate = baseFireRate * bonusSpeed;
}
else {
fireRate = baseFireRate;
}
}

Awesome that worked! Thanks @StarManta !