Why my score it going down really fast when using Time.deltaTime?

Why my score it going down really fast when using Time.deltaTime? I’m trying to make a score system when every second you loss 1 point, but when I try to do this it make it go everything fast. I tried playing around with the TimeScale, fixed update, fixedtime and stuff but nothing to seem to work. Is this something have to do with the UI? What am I doing wrong? Here’s my code

public float timer = 0;
    private string currentTime;
    Text text;

    void Start()
    {
        text = GetComponent<Text> ();
        score = 50000;
    }

    void Update()
    {
        timer += Time.deltaTime;
        currentTime = string.Format ("{0:0}", timer);

        score -= (int) timer;

        if (score < 0)
            score = 0;

        text.text = "" + score;
    }

You can link me to other questions are like this if there are.

It seems like the timer goes down and the score goes up

I know i was playing around with this so ill change it. And for some reason its doing the same thing.

The mistake you’ve made is that you increase the timer then take it away from the current score. So it won’t remove 1 a second it will remove the time elapsed every frame.

You can do something like this to get what you want. Alternatively you can change the line “score -=(int) timer;” to “score -= Time.deltaTime;”

public float timer = 0;  
private string currentTime;   
Text text;
int baseScore;
int curScore;

void Start()  {      
text = GetComponent<Text> ();      
baseScore = 50000; 
}  

void Update()   {       
timer += Time.deltaTime;       
currentTime = string.Format ("{0:0}", timer);       
curScore = Mathf.RoundToInt(baseScore - (int) timer);
if (curScore < 0)
curScore = 0;
text.text = "" + curScore;  
}
1 Like

Thank you LordConstant, it works and now i understand! :slight_smile:

Hmm, I’m more a C++ then a C# person, but wouldn’t the following be much more simple.

    private float lastTime;

    void Start() {
        lastTime = Time.time;
    }

    void Update () {
        if (Time.time - lastTime > 1) {
            score--;
            lastTime = Time.time;
        }
    }

Greets,

Jan

1 Like

At that point you are just calculating the delta time though. Which can be accessed with Time.deltaTime.

But you are right that way can be done. I just decided to adapt the code to fit with the current method.

1 Like