Quick Timer Question

Hi - a quick question - I’m trying to get it so that when i enter the triggerzone a timer counts down from 5 - and when i exit the triggerzone it waits for 2 seconds, then begins to count up. However, the only things that are working are the counting down and the wait for 2 seconds. I’m guessing ‘timer += Time.deltaTime’ means that your counting up? Because instead when i leave the triggerzone the timer stops and does’nt start to count up.

#pragma strict

var Player : Transform;
var timer : float = 2;


function Start () {
    light.color = Color.red;
 
}
function OnTriggerEnter (Player : Collider) {
    print("InTrigger");
}
function OnTriggerStay (Player : Collider) {
    print("InTrigger");
    timer -= Time.deltaTime;
    if(timer <= 0)
    {
        timer = 0;
        light.color = Color.blue;
    }
}
function OnTriggerExit (Player : Collider) {
    print("OutTrigger");
    timer += Time.deltaTime;
    light.color = Color.red;
}

function OnGUI () {
    GUI.Label(new Rect(300, 100, 100, 20), (timer.ToString()));
}

Thanks
-Fin

yup you’re correct.

And the reason it’s not counting up is because it needs to be modified in update or in a coroutine.

if you create a bool for your count up variable. then when you leave your trigger set it to true. if it’s true (in update) then count up

something like this:

#pragma strict

var leftTrigger : boolean = false;
var timer : float;

function Update () {
    if(leftTrigger) {
        timer += Time.deltaTime;
    }
}

function OnTriggerEnter (player : Collider) {
    leftTrigger = false;
}

function OnTriggerExit (player : Collider) {
    leftTrigger = true;
}

Thank you, i’ll try that.
-Fin

OnTriggerEnter, OnTriggerExit, GetKeyDown etc. they all only fire on the one frame when the thing happens. To make use of these “over time” you need to do as smitchell suggests, bools, coroutines etc.

OnTriggerStay, GetKey etc. trigger every frame.

Ok i’ve tried that code - yes, it does count up - i’ve then got a enterTrigger = -= Time.deltaTime, which is true when i enter the trigger and false when i leave. This however gives me alot of errors - like semicolons at the end when there already is one there and wiggly brackets expected when there is already on there. Do you know how to get it so i still countdown on the timer?

Dont worry - i’ve fixed it - i just had this:

function Update () {
    if(leftTrigger) {
        timer += Time.deltaTime;
    }
    else
        timer -= Time.deltaTime;
}