Skip to content
Matheus Lessa Rodrigues edited this page Nov 9, 2017 · 5 revisions

Timer

A simple timer for your MonoBehaviours. Given a timer length and a callback, the callback will be called after that many seconds have elapsed once the timer is started. It is possible to edit its length in the inspector.

It's a type-safe alternative to Invoke( methodName, delay ).

Note

Do not forget to call timer.OnUpdate() inside your MonoBehaviour.Update() in order to update its internal state.

Example

using UnityEditor;
using BitStrap;

public sealed class MyScript : MonoBehaviour
{
    // Create a timer with a default length of 2 seconds.
    // It's length can be changed in the inspector :)
    public Timer myTimer = new Timer( 2.0f );

    private void OnTimer()
    {
        Debug.Log( "{0} seconds have elapsed", myTimer.length );
    }

    private void Awake()
    {
        myTimer.onTimer.Register( OnTimer );
    }

    private void Update()
    {
        myTimer.OnUpdate();
    }
}

If you need extra precision control, you can use Timer.onTimerPrecise which is very similar to Timer.onTimer but it will also give you a float latency parameter. It represents how much latency your callback was called with.

Also, you can make a looping timer (one that as soon it ends, it starts again) by using this pattern:

private void Awake()
{
    // As soon as it calls, the timer will be restarted
    myTimer.onTimerPrecise.Register( myTimer.Start );

    myTimer.onTimer.Register( /* others callbacks */ );
}
Clone this wiki locally