Does Unity3D have a Timer Class

Hello

Is there a way to make a method execute at a specific time?

For example:

public void showMessageBox() {
    this.gameObject.SetActive(true);

    SetTimer(3000, hideMessageBox);  // after 3 seconds hide message box
}

Note I am aware I can implement my own timer using Update and a boolean variable. But I’d rather use an existing Unity3d Timer class method (if it exists) before I reinvent the wheel. I also want to use Unity3d’s timer as it has most likely been optimised and tested.

void Update() {

    // Having this method run every game loop is really inefficient in my opinion
    if (!this.gameObject.GetActive())
        return;
    if (timeRemaining <= 0)
        this.gameObject.SetActive(false);

    timeRemaining--; // TODO: compensate using delta time
}

You could use invoke.
So, for example:

Invoke(“hideMessageBox”, 3);

The main way that is pushed with Unity would be to implement it as a coroutine like follows:

public IEnumerator ShowMessageBox() {
    showing = true;
    yield return new WaitForSeconds(3);
    showing = false;
}



void OnGUI() {
    if (showing) {
        //Draw message box of whatever
    }
}

Using C#, you need to use the IEnumerator return type so the engine knows that the function is a co-routine. Unityscript will automatically type the function as needed if you use ‘yield’ inside of it.

There are tons of ways to solve this problem, and using a float ‘timeout’ is also valid.

Also, just an FYI, inactive GameObjects do not run ANY Update functions on any behaviours, so you can’t reliably activate/deactivate game objects the way you were thinking you can.

Edit: changed

yield WaitForSeconds(3); 

to

yield return new WaitForSeconds(3);

to match C#'s syntax.
Unity script automatically adds those as well.