Reputation: 53
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.
Upvotes: 3
Views: 9935
Reputation: 1
I know I am a bit late to answer, but the same can be done with Mathf.FloorToInt(Time.timeSinceLevelLoad)
Upvotes: 0
Reputation: 127603
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;
}
}
Upvotes: 5