Write your own Unity Timer Class for Global usage

This Class can be Handy in many cases and can be used for many different Aspects. We are going to Create a Timer Class and Wrap a MonoBehaviour Up to perform the Update Method.

Create a Timer Class

This class is handy in many cases and can be used for many different aspects. We will create a Timer class and wrap a MonoBehaviour to perform the update method.

This is a basic version of a timer class in Unity, this timer class can be extended with an object pool and other useful assets to achieve better performance.

Call a Timer

				
					        //A Common Use would be to Turn off a Object  after a period of Time
        MyTimer.CreateTimer(() => GameObject.SetActive(false), 1);
				
			

A timer can be created within the assembly by calling:

MyTimer.CreateTimer( () => Action, Time).

After the time has expired, the MonoBehaviour hook we created will destroy the GameObject by itself.

This method creates an overhead on the CPU. You can avoid this by creating a pool and list of timers that can be reused.

You should keep this in mind if you use the Timer class very often.

public class MyTimer

Create  MyTimer.cs

				
					/// <summary>
/// Create a Timer on a MonoBehaviour GameObject
/// After Time runs out a Action can be called.
/// </summary>
public class MyTimer 
{
    /// <summary>
    /// We Call this Function from other Scripts to Create a Timer at Runtime
    /// </summary>
    /// <param name="action">The Action that gets Performed after the Time runs out.</param>
    /// <param name="timer">The amount of Time that has to pass until the Timer gets Triggered</param>
    /// <returns></returns>
    public static MyTimer CreateTimer(Action action, float timer)
    {
        GameObject obj = new GameObject("TimerObject", typeof(MonoBehaviourHook));
        MyTimer stTimer = new MyTimer(obj, action, timer);
        obj.GetComponent<MonoBehaviourHook>().OnUpdate = stTimer.UpdateTimer;

        return stTimer;
    }

    //We Store the GameObject so we can Destroy it later
    GameObject gameObject;

    float timer;
    Action TimeAction;


    public MyTimer(GameObject gameObject, Action action, float timer)
    {
        this.gameObject = gameObject;
        this.timer = timer;
        this.TimeAction = action;
    }

    /// <summary>
    /// Update the Time with OnUpdate from Monobehaviour.
    /// </summary>
    void UpdateTimer()
    {
        timer -= Time.deltaTime;

        if (timer > 0)
            return;

        TimeAction();
        DestroySelf();        
    }

    /// <summary>
    /// GameObject gets Destroyed after TimeAction is performed
    /// </summary>
    void DestroySelf()
    {
        GameObject.Destroy(gameObject);
    }

    /// <summary>
    /// We add a Simple Script on our GameObject
    /// With this we have the Update Method available which will Trigger our Action
    /// After a certain amount of Time.
    /// </summary>
    class MonoBehaviourHook : MonoBehaviour
    {
        public Action OnUpdate;

        private void Update()
        {
            if (OnUpdate != null) OnUpdate();
        }
    }
}
				
			

This is an Example Timer Class

This is a very simple timer function that performs an action after the set time expires. It uses the MonoBehehaviours update method and may not be the best solution or approach. It should depend on your game project, what kind of timers you need and how strongly they are typed.

This little class can be used in almost any Unity project to implement a timer quickly and easily!

Leave a Reply

Your email address will not be published.