Search code examples
c#unity-game-enginetimergame-development

How to make powerup timer?


I want to make countdown timer that will return value of bool when he is active , so I can check on other script if is active give double points if is not then you need to give normal points.. I want to make it more complicated and I want to add time on timer if the timer is active, if is not then we use default time on countdown...

I don't know how to use courutine specially when I need to add time if the timer is not over..

Lets say like a example: I pick up power up and timer starts for 5 seconds counting to 0. If i pick up again powerup and timer is on lets say 3 , Power up need to have now 8 seconds. When powerup is over he must go from 5 seconds when player pick up new one..

Here is my code that doesn't work how I want also my code doesn't have a function to add time to power up when power up is active.. In other words I don't know how i can check if powerup is active and if yes just to add to counter 5 more seconds..

Here is code that doesn't contain adding time it only contains working counter..

 void startDoublePoints()
{
    StartCoroutine("doublePoints");
    Time.timeScale = 1;
}
//Simple courutine
IEnumerator doublePoints()
{
    while (true)
    {
        yield return new WaitForSeconds(1);
        timeLeft--;
    }
}

I hope someone will explain me more about how I can achieve my goal.. I hope I explained what I need to achieve.. If you do not understand something please ask on comment and I will try to explain it again..

Thank you so much community I don't know how would I learn anything without this great place :)


Solution

  • float powerUpTimer;
    bool isDoublePoints = false;
    
    void Update()
    {
        // Check timer only when Power up time
        if(isDoublePoints)
        {
            // Countdown the timer with update time
            powerUpTimer -= Time.deltaTime;
            if(powerUpTimer <= 0)
            {
                // End of power up time 
                isDoublePoints = false;
                powerUpTimer = 0;
            }
        }
    }
    
    // Add any time player picks to timer
    public void OnPickPowerUp(float buffTime)
    {
        isDoublePoints = true;
        powerUpTimer += buffTime;
    }