Search code examples
c#unity-game-enginetimer

Cooldown timer for an incremental game


I'm trying to make a game in unity (which uses c#) and what I am trying to accomplish is almost identical to what is done in the game Adventure capitalist. When you click on one of the companies, there is a "cooldown" timer. I put that in quotations because you don't get the money until after the timer has finished. I have looked at the other suggested questions and have managed to create the code below

public UnityEngine.UI.Text showCurrency;
public int money = 0;
public int moneyPerClick = 1;
public float timeToCollect = 3.0F;
private float timeStamp;
private bool buttonClicked;    

void Start()
{
    timeStamp = Time.time + timeToCollect;
}

void Update()
{
    showCurrency.text = "Money: " + money;
    if(buttonClicked && timeStamp > 0.0F)
    {
        timeStamp -= Time.time;
            
    }
    if (timeStamp == 0.0F)
        {
            money += moneyPerClick;
        }
}

public bool Clicked()
{
    buttonClicked = true;
    return buttonClicked;        
}

I currently get 1 error but that started happening after I added the showCurrency.text = "Money: " + money; part. So that needs to be fixed.

The code, as far as I can tell, it not working. I don't have the cooldown effect working with the image fill (which will be a problem for another day) So I can't actually see if the timer is counting down, but I guess I could have a Debug.Log and have a system.out line to test that. The other thing that isn't working is I'm not getting the new money amount to show up on screen.

This code is a beginners best guess at how it would be layed out and it is where I'm at. If it looks like I am using the methods wrong, that's probably because I am. Any further information to at least point me in the right direction would be greatly appreciated.


Solution

  • Unity's Update() method gets called every frame. So if you have the game set to 30 FPS, then Update() will get called 30 times every second.

    Firstly, timeStamp -= Time.time subtracts the current time from your stored time every single frame (it gets to be a realllly small number really fast). As you have it, try changing your second if statement to an inequality check instead of checking for equality: if (timeStamp <= 0.0F)

    Alternatively, your Update() function could be simplified to something like this:

    void Update()
        showCurrency.text = "Money: " + getMoney();/*Make money into a property with a getter and setter, so that it will be easily changeable at run-time*/
        if(buttonClicked && (Time.time >= timeStamp)) 
        {
            timeStamp = (Time.time + timeToCollect);
            setMoney(getMoney() + moneyPerClick);
            buttonClicked = false; /*Reset your button to be clickable again*/
            /*You could also setup your setMoney() like setMoney(moneyPerClick), but that's not what you asked ;b*/
        }
    }