private var startTime;
var textTime : String; //added this member variable here so we can access it through other scripts
function Awake() {
startTime = Time.time;
}
function OnGUI () {
var guiTime = Time.time - startTime;
var minutes : int = guiTime / 60;
var seconds : int = guiTime % 60;
var fraction : int = (guiTime * 100) % 100;
text = String.Format ("{0:00}:{1:00}:{2:000}", minutes, seconds, fraction);
GUI.Label (Rect (400, 25, 100, 30), textTime); //changed variable name to textTime -->text is not a good variable name since it has other use already
}
In your OnTriggerEnter function you then have to write the following to access the time when the trigger was entered (adjust "Main Camera" and "Timer" to whatever your game object and script name are that contain your timer):
function OnTriggerEnter (other : Collider) {
var timeTrigger = gameObject.Find("Main Camera").GetComponent("Timer").textTime;
Application.LoadLevel (1);//or whatever the number of your new level is
}
you should get the time.time in a awake or start function in new scene and then subtract the current time.time from the first value. somethings like this
var t,ellapsed;
function Start ()
{
t=time.time;
}
function Update ()
{
ellapsed=time.time-t;
}
I know the topic is kinda old, but in case anyone needs it…
For a reversed time I guess you could initialize a variable “goalTime” with the current time plus the amount of seconds you want to wait.
I just used Sebas answer and modified a little bit.
private var goalTime;
private var totalTime = 30.0; //the amount of time you want to start the countdown;
var textTime : String; //added this member variable here so we can access it through other scripts
function Awake() {
goalTime = Time.time + totalTime;
}
function OnGUI () {
var guiTime = goalTime - Time.time; // You probably want to clamp this value to be between the totalTime and zero
var minutes : int = guiTime / 60;
var seconds : int = guiTime % 60;
var fraction : int = (guiTime * 100) % 100;
text = String.Format ("{0:00}:{1:00}:{2:000}", minutes, seconds, fraction);
GUI.Label (Rect (400, 25, 100, 30), textTime); //changed variable name to textTime -->text is not a good variable name since it has other use already
}
If anyone needs it today…
there is a better way than Time.deltaTime. You can use IEnumerator with yield return new WaitForSeconds();
using System.Collections;
using UnityEngine;
public class Timer : MonoBehaviour {
float _timer = 60;
bool _active = true;
private void Start()
{
StartCoroutine("timer");
}
IEnumerator timer()
{
while (_active)
{
yield return new WaitForSeconds(1);
_timer--;
Debug.Log(_timer);
if (_timer == 0)
_active = false;
}
Debug.Log("Game Over");
}
}
yield return new WaitForSeconds(1); just means that the programm waits a second and than goes on.
If you want to change the value, you can easy do it in that line in the brackets, but if it is to low, like 0.01f it don’t work very well.