How do I decrease a number after a certian amount of time has passed?

Updated on October 20, 2019 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on October 18, 2019


I am trying to create a powerup system in my game right now and the way that I have set it up is if the player passes through an object a number will increase by 1. And after the player passes through this object 4 times the powerup will get enabled. What I am trying to add to this is when the player passes through the object once the number gets set to one after a certain amount of time passes without the player going through the object again the number goes down by 1. If the player goes through the object before the timer reaches 0 then the number should go up by 1 again. This is what I have tried.



     while(comboNumber >= 1)
     comboNumber -= 1;

    IEnumerator ComboWait()
    yield return new WaitForSeconds(1f);

All that is happing from this is the comboNumber is never going up. It always stays at zero. I have tried adding a bigger delay but the comboNumber never seems to go up. The while loop is in the update function. If anybody has any suggestions that would be great!


  • Liked by
1 on October 18, 2019

Coroutines are one way to go about doing this, but the implementation is a bit off.

It’s staying at 0 because your if statement says if >= 1, subtract 1. As it is, it doesn’t care about the coroutine.

Corutines are more like a new thread, not just a wait timer. Try moving comboNumber -= 1; to be inside your coroutine, and see how that works.

However, just doing that wont give you your desired results., because as it is, you’ll be starting the coroutine EVERY FRAME that combo >= 1, which means that once the 1st timer has expired, you still have about 59 MORE coroutines still running waiting to be finished.


What might be easier, is to just store some time value, and whenever they get a power-up, reset it. Something like this.


public class Player
     private float powerUpTime;
     public float powerTimeRemaining
     private int _comboNumber;
     public int comboNumber
          get => _comboNumber;
               _comboNumber = value;
               powerTimeRemaining = powerUpTime;
     void Update()
     void HandlePowerTimer()
          if(comboNumber <= 0) return;
          else if(powerTimeRemaining <= 0)
               comboNumber -= 1f ;
               powerTimeRemaining -= Time.deltaTime;


edit: forgot to mention that this works both ways. Once the time has expired, it will go down by one and reset, but once you pick another one up, even if the time is about to expire, it resets it back to full.


edit 2: added extra check if combo is already 0, so it doesn’t go negative  =p

on October 20, 2019

Thanks so much for the reply!! I was able to add the suggestions that you made and I was able to get it to work!


Thanks again!

Show more replies
  • Liked by