Timer Question

var endTime : float;
var textMesh : TextMesh;

function Start()
{
    endTime = Time.time + 60;
    textMesh = GameObject.Find ("Timer").GetComponent(TextMesh);
    textMesh.text = "60";
}

function Update()
{
    var timeLeft : int = endTime - Time.time;
    if (timeLeft < 0) timeLeft = 0;
    textMesh.text = timeLeft.ToString();
}

Hi all here is the code that I get from this site. I’m planing to use this kind of timer. The problem is this timer countdown start from the first frame.

I want to have a countdown Timer which start after an event is triggered. Anyone have anyidea?

Hi there.

Have you tried using Time.Deltatime instead of Time.time? There is a good explanation of how it works here:

Yeah. So, first, start off with a timer variable (a float) initialized to 0. Then, when your desired event happens, set this timer to how long you want it to count for (in seconds). Finally, in your Update function, you can do something like:

if (timer > 0)
{
    timer -= Time.deltaTime;
    if (timer <= 0)
    {
        timer = 0;
        //do whatever else you want here
    }
}

That will tick down the timer and do your desired action only once.

You need to add a boolean. Let’s say you want to start the timer when the player enter a zone. Add a box collider and tick IsTrigger. Then add this to the box:

var isIn:boolean;
var timer:float;

function Start(){
  isIn = false;
}

function Update(){
  if(isIn){
    timer += time.deltaTime;
    if(timer > second){
      //Do something
      //If you want the timer to restart
      timer = 0;
    }
  }
}

function OnTriggerEnter(other:Collider){
  if(other.gameObject.tag =="Player"){
    isIn= true;
     timer = 0;
  }
}

function OnTriggerExit(other:Collider){
  if(other.gameObject.tag =="Player")
     isIn= false;
}