- Home /
Easiest way to create a timer?
Hello unity3D.I have a question about timers?What is the easiest way to create a timer in javascript?For example,my characters does this kind of move that makes the camera move to another position and i need a timer because i want the camera to go back to the starting point whenever there is no collision happening more than 2 secs.if anyone knows how i can do this?Can you please tell me how?
Generally, I just make a float and set it equal to the time I want in seconds. And, during update, subtract Time.deltaTime until the float is equal to or less than 0.
float timerTime = 2.0f;
bool timerSet = true;
void Start(){
}
Update(){
if(timerTime <= 0 && timerSet){
timerSet = false;
//Do something
}else{
timerTime -= Time.deltaTime;
}
}
Answer by nullgobz · Aug 11, 2015 at 02:41 AM
Untested, just set timerActive to true to start timer again.
var time : float;
var timer : float;
var timerActive : bool;
void Start()
{
timerActive = true;
time = 2.0;
}
void Update()
{
timer += Time.deltaTime;
if(timer >= time && timerActive)
{
//Move Camera
timerActive = false;
timer = 0.0;
}
}
Answer by Skflowne · Aug 11, 2015 at 03:52 AM
You could use a coroutine like so :
IEnumerator DoAfterTime(float time){
yield return new WaitForSeconds(time);
// do something after time
}
void StartTimer(){
StartCoroutine(DoAfterTime(2f));
}
I guess this could be improved further by passing a callback function to the coroutine and calling it in place of "do something"
This solution unfortunately won't work for OP's situation because the timer cant't be stopped and reset midway. If a collision happens within 2 seconds, the IEnumerator will continue running.
Who says that the timer can't be stopped? The only subject of this coroutine is to be a timer, thus a StopCoroutine will stop it. There is no hard work on relaunching a new one rightafter.
And by the way, from my point of view and many others, this way of playing with time is more efficient. No call to Update is always a good point.