- Home /
Timer will not reset properly.
In the game I am making, there are "dummies" that the player shoots at. When the player shoots them they disappear. The game is a time trial to shoot all of the dummies as fast as possible.
Here is my problem:
I can't get the timer to reset. I have gotten it to stop when all of them are shot, but when i press "R" to reset, the timer goes back to zero when I cross the trigger, but when i finish the map for the second time, the time just adds on with the previous attempt.
I have figured out through hours of research that Time.time is my problem. I cant reset Time.time to zero. I have tried many different things trying to get it to reset correctly and I have run out of ideas.
I am posting my code on this question as well as a YouTube video of me explaining my problem. Thanks in advance for your help :D
YouTube Link:
Shooting Frenzy Help Video
Sorry for the bad audio... it didn't record correctly...
using UnityEngine;
using System.Collections;
public class GameControllerTime : MonoBehaviour {
private static int dummyAmount;
private static float startTime, endTime;
private static float elapsedTime;
public string currentLevel;
public GUIStyle timer;
public Rect rect = new Rect(300, 25, 100, 200);
// Use this for initialization
void Start () {
dummyAmount = GameObject.FindGameObjectsWithTag ("Dummy").Length;
startTime = 0;
}
public static void RemoveDummy(){
/* I have another script attached to the dummies that triggers this function*/
dummyAmount--;
if (dummyAmount <= 0) {
endTime = Time.time;
elapsedTime = endTime - startTime;
}
}
void Update () {
if (startTime > 0)
{
elapsedTime = Time.time - startTime;
}
/* This reloads the level when "r" is pressed, it could go in another scrpit if needed.
It resets the dummies but not the timer. */
if (Input.GetKeyDown (KeyCode.R)) {
Application.LoadLevel (currentLevel);
}
}
void OnTriggerEnter(){
/* walk through trigger to start timer */
startTime = Time.time;
}
void OnGUI(){
/*puts timer on screen*/
if (dummyAmount >= 1) {
GUI.Label (rect, (elapsedTime.ToString ("F2")), timer);
rect.x = 20f;
rect.y = 20f;
}
else {
GUI.Label (rect, (endTime.ToString ("F2")), timer);
rect.x = 20f;
rect.y = 20f;
}
}
}
no, it didn't work.
sorry for taking so long to get back to this... i've had school and such to work on ;)
Answer by cryingwolf85 · May 30, 2014 at 05:55 AM
Ahh, some of this code looks familiar ;) Anyway...
The starting time needs to be set to the current time, so when you subtract the start time from the end time you are getting a meaningful number. Just change line 19 to
startTime = Time.time;
and your problem is solved.