How do I make an timer?

So I want an object to become active and inactive again in a loop.
How would i do this, I would also like it if I can edit the timing in the editor.

Thanks :smile:

Using: Unity 5, C#

http://bfy.tw/GXi

sorry… couldn’t resist

2 Likes
using UnityEngine;
using System.Collections;

public class MyTimer : MonoBehaviour {
   
    public float interval = 0.2f; // PUBLIC SO YOU CAN CHANGE IT IN INSPECTOR
    float waitTime;

    void Awake () {
        waitTime =0;
    }

    void Update () {
       
        if (waitTime <= 0) {
            /*
            / DO SOMETHING HERE
            */
            waitTime = interval;
        }
        waitTime -= Time.deltaTime;
    }
}

:wink:

1 Like
public bool isActive = false;
public float maxActivityTime = 5f;
public float currentActivityTime;
void OnUpdate(){
    if(isActive == true){
 currentActivityTime =+ time.deltatime;
        if(currentActivityTime < maxActivityTime){
            //dosomething
        }
        else{
            isActive = false;
        }
    }
}

void StartActivity(){
    isActive = true;
    currentActivityTime = 0f;
}
1 Like
IEnumerator StartTimer(float t) {
  yield return new WaitForSeconds(t);
  //do stuff
}
2 Likes

If you must use it in Update(), use @Duugu 's or @Thibault-Potier 's solution. Otherwise, learn how to use coroutines safely and use @dterbeest 's solution.