How do I reset the time after the game fail? The time just keeps decreasing in my game even after the game over scene is played out and it restarts back to the main scene.
This is my script attached to the GUI for time:
#pragma strict
private var startTime;
var restSeconds : int;
private var roundedRestSeconds : int;
private var displaySeconds : int;
private var displayMinutes : int;
var countDownSeconds : int;
function Awake() {
startTime = countDownSeconds;
}
function Update ()
{
guiText.text = String.Format ("{0:00}:{1:00}", displayMinutes, displaySeconds);
}
function OnGUI () {
var startTime: float;
var guiTime: float = Time.time - startTime;
restSeconds = countDownSeconds - (guiTime);
if (restSeconds == 60) {
print ("One Minute Left");
}
if (restSeconds == 0) {
print ("Time is Over");
LevelFail();
}
roundedRestSeconds = Mathf.CeilToInt(restSeconds);
displaySeconds = roundedRestSeconds % 60;
displayMinutes = roundedRestSeconds / 60;
}
function LevelFail()
{
Application.LoadLevel("GameOver");
startTime = 240;
}
My countDownSeconds is set to 240 in the inspector. Thank you! ![]()
Time.time is a counter of the total number of seconds since the beginning of the game. If you define your countdown in terms of it, the countdown will continue to decrease even if you reset the level! Time.deltaTime, on the other hand, is the amount of time between the last time Update was called and now- so if you have a countdown float countdown, and then use countdown -= Time.deltaTime; once every Update, then it will decrease at a constant rate of one per second. This is a much more general way of implementing a countdown, and will reset automatically when you load the level!
– syclamothWhy does the countdown have to be an int? I don't understand this. There is no reason why it can't be a float instead- if there's any time when you absolutely need it to be an integer you can just use Mathf.RountToInt(countdown) to turn it into an int temporarily.
– syclamothYes, the time starts at 240, but there isn't a reason why you can't make that a float! Floats can count down just as easily as integers can. Also, you can still reset it if its a float! If the problem is that you need to display it as exact seconds, then just do what I said in my previous comment and round it to an integer whenever you want to display the time.
– syclamothRemember that if you do the whatever -= time.deltaTime thing inside of the OnGUI function, it will be called at least three times a frame- meaning that your timer will count down much too fast. It needs to happen inside of Update, and it needs to happen once only.
– syclamoth