Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Based Scoring Unity

Hi I'm a beginner in unity and I want to be able to add 10 points to the score every 5 seconds since the game started, this is how i tried to implement it

private int score;
void Update () {

    Timer = Time.time;

    if (Timer > 5f) {

        score += 5;
        Timer -= 5f;
    }
    ScoreText.text = score.ToString ();

 }

this is not working what happens is the score increases rapidly after 5f and then it crashes my game.

like image 763
user3679986 Avatar asked Aug 23 '26 10:08

user3679986


1 Answers

The math for calculating every 5 seconds is wrong. You should not be doing Timer = Time.time; every loop, that just throws away the old value of Timer. Use Time.deltaTime and add it to the timer instead.

 //Be sure to assign this a value in the designer.
 public Text ScoreText;

 private int timer;
 private int score;

 void Update () {

    timer += Time.deltaTime;

    if (timer > 5f) {

        score += 5;

        //We only need to update the text if the score changed.
        ScoreText.text = score.ToString();

        //Reset the timer to 0.
        timer = 0;
    }
 }
like image 99
Scott Chamberlain Avatar answered Aug 25 '26 00:08

Scott Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!