- Home /
How to make a Time Based Score?
I've seen a lot of question in this forum but i can't find one that I wanted. So basically what i wanted to do is I wanted to make a time based score, It's will works like this. So the game will have a countdown timer started at 60 seconds, each 20 seconds spend will deduct 1 star. The score(stars) will show at the result scene which is a different scene from the game. Please help me solve this problem. Thank you!
Answer by Harinezumi · Apr 16, 2018 at 08:35 AM
Use a small class to keep the time, and determine remaining points based on the remaining time. To display number of stars just query this class every now and then. To display the score in a different scene, the easiest way is to store it in a static variable somewhere, but make sure that you reset it every time you start a new level.
public class LevelTimer : MonoBehaviour {
// set it to true when gameplay has started, to false when level finished or game paused
private bool timerRunning = false;
public void SetTimerRunning (bool value) { timerRunning = value; }
private float remainingTime = 60.0f;
private void Update () {
if (timerRunning) {
remainingTime -= Time.deltaTime;
}
}
// call from anywhere you want to know how many stars remain. Mathf.Clamp() used to not go below 0 or above 3
// +1 added to form the following pattern: 40-60 seconds = 3 stars, 20-40 seconds = 2 stars, 0-20 seconds 1 star, 0 stars otherwise
public int GetPoints () {
return Mathf.Clamp((int)(remainingTime / 20) + 1, 0, 3);
}
}
This is a good answer. However I'd make the remainingTime a public variable as well as the hardcoded values on GetPoints() in order to get more flexibility.
Yes, making the calculations more configurable would be better, but I didn't want to confuse the OP with it. It could be even more flexible if the time limits were defined in a list and a loop would check within which limits the remaining times is. Something like this:
[SerializeField] private List timeLimits = new List(); // list of time limits in increasing order, for example 0, 20, 40
public int GetPoints () {
for (int i = 0; i < timeLimits.Count; ++i) {
if (remainingTime < timeLimits[i]) { return i; }
}
return timeLimits.Count;
}
Your answer
Follow this Question
Related Questions
Game Timer help needed 2 Answers
How to make a timer read to the .001 of a second 2 Answers
Multiple Cars not working 1 Answer
Timer doesn't work properly 2 Answers
timer not ticking down 2 Answers