# How to make a new powerup reset the WaitForSeconds from previous powerup?

I'm making a game where the player is pushing objects outside a plane. Every round there's an additional ball (GameManager.cs):

 for (int i = 0; i < enemiesToSpawn; i++)


But every round the player gets a powerup as well:

 if (enemyCount == 0)
{
roundNumber++;
SpawnEnemyIntruders(roundNumber);
Instantiate(powerup, GenerateSpawnPosition(), powerup.transform.rotation);
}


In the PlayerController.cs the code looks like this:

   private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Powerup"))
{
hasPowerup = true;
Destroy(other.gameObject);
StartCoroutine(PowerupCountdown());
powerupParticle.Play();
playerAudio.PlayOneShot(powerupSound, 1.0f);
}
}

IEnumerator PowerupCountdown()
{
yield return new WaitForSeconds(5);
hasPowerup = false;
powerupParticle.Stop();
}


How can I reset the WaitForSeconds, or do something similar, every time the player gets a powerup?

You could have a timer as class' member instead of a local variable in your coroutine.

private float powerupTimer;
private IEnumerator powerupCoroutine;

private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Powerup"))
{
hasPowerup = true;
Destroy(other.gameObject);
powerupTimer += 5;
if(powerupCoroutine != null)
StopCoroutine(powerupCoroutine);
powerupCoroutine = PowerupCountdown();
StartCoroutine(powerupCoroutine);
powerupParticle.Play();
playerAudio.PlayOneShot(powerupSound, 1.0f);
}
}

IEnumerator PowerupCountdown()
{
for(; powerupTimer > 0 ; powerupTimer -= Time.deltaTime)
yield return null;
hasPowerup = false;
powerupParticle.Stop();
}


However, I believe you should rework your power up system. The player class should not be responsible for all this logic (handling timer, particles, ...)

• Thank you! I'll try to clean up my code. I'll try to move as much as possible into the GameManager and/or make a cs-file just for the powerup. It's my first game ever, so I'm learning a lot along the way. – Senseless Nov 10 '19 at 22:01
• And just so I'm entirely sure how to understand every bit of the code: What does the first semicolon mean? for(; powerupTimer > 0 ; powerupTimer -= Time.deltaTime) – Senseless Nov 13 '19 at 9:04
• I know it's the initializer, but why can it be empty in this case? – Senseless Nov 13 '19 at 9:52
• It's empty because we don't want to give an initial value to powerupTimer. The value is "reset" in the OnTriggerEnter function. – Hellium Nov 14 '19 at 9:36