- Home /
timer problem
Whenever the game starts and enters the scene that is containing the script then the variable myTimer will be set to zero and so will the Time.time so that the game can be played again from the start with the time counting up from zero instead of from where the last game ended. This is the script I have but it doesn't do what I have just described. How can this be done?
using UnityEngine;
using System.Collections;
//ATTACH TO MAIN CAMERA, shows your health and coins
public class GUIManager : MonoBehaviour
{
public GUISkin guiSkin; //assign the skin for GUI display
[HideInInspector]
public int coinsCollected;
public float LastTime;
public float BestTime;
float time = Time.time - Time.time;
float myTimer;
private int coinsInLevel;
private Health health;
//setup, get how many coins are in this level
void Start()
{
coinsInLevel = GameObject.FindGameObjectsWithTag("Coin").Length;
health = GameObject.FindGameObjectWithTag("Player").GetComponent<Health>();
myTimer = Time.time - Time.time;
}
void Update()
{
myTimer = time;
}
//show current health and how many coins you've collected
void OnGUI()
{
GUI.skin = guiSkin;
GUILayout.Space(5f);
if(health)
GUILayout.Label("Time: " + myTimer.ToString("F2"));
if(coinsInLevel > 0)
GUILayout.Label ("Gifts: " + coinsCollected + " / " + coinsInLevel);
if(coinsCollected > 9)
Application.LoadLevel("Menu");
}
}
Answer by highpockets · Dec 21, 2013 at 07:05 AM
You have the variable time = Time.time - Time.time; declared at the top, outside any function. That will return 0.
In the Start function, you also have another variable, myTimer = Time.time - Time.time; That will return 0,
Then you assign the variable, time to myTimer. That is the same as 0 = 0…
I'm pretty sure you wound up with 0 over and over again on your GUI label, right?
Time.time is read only, so you cannot change it, but if you just assign Time.time to the myTimer variable in the start function, then you can subtract it from Time.time to find the time that has passed since you started.
using UnityEngine;
using System.Collections;
//ATTACH TO MAIN CAMERA, shows your health and coins
public class GUIManager : MonoBehaviour
{
public GUISkin guiSkin; //assign the skin for GUI display
[HideInInspector]
public int coinsCollected;
public float LastTime;
public float BestTime;
float myTimer;
float newTime;
private int coinsInLevel;
private Health health;
//setup, get how many coins are in this level
void Start()
{
coinsInLevel = GameObject.FindGameObjectsWithTag("Coin").Length;
health = GameObject.FindGameObjectWithTag("Player").GetComponent<Health>();
myTimer = Time.time;
}
void Update()
{
newTime = Time.time - myTimer;
}
//show current health and how many coins you've collected
void OnGUI()
{
GUI.skin = guiSkin;
GUILayout.Space(5f);
if(health)
GUILayout.Label("Time: " + newTime.ToString("F2"));
if(coinsInLevel > 0)
GUILayout.Label ("Gifts: " + coinsCollected + " / " + coinsInLevel);
if(coinsCollected > 9)
Application.LoadLevel("Menu");
}
}