Skip to content

Instantly share code, notes, and snippets.

@ritobanrc
Last active March 13, 2018 01:23
Show Gist options
  • Save ritobanrc/4a8f210e3c035df1f2c0648a59d1394f to your computer and use it in GitHub Desktop.
Save ritobanrc/4a8f210e3c035df1f2c0648a59d1394f to your computer and use it in GitHub Desktop.
A Timer class in Unity. Requires my Singleton class.
/* Timer.cs
(c) 2017 Ritoban Roy-Chowdhury. All rights reserved
*/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Timer
{
public float TotalTimeElapsed { get; protected set; }
protected float ExpireTime;
protected Action<float> updateWrapper;
protected Action expireWrapper;
// NOTE: To create repeating timers, simply Reset the timer when it expires
public Timer(float time, Action<float> updateAction, Action expireAction)
{
this.ExpireTime = time;
this.updateWrapper =
(dt) =>
{
TotalTimeElapsed += dt;
if (TotalTimeElapsed >= ExpireTime)
{
if (this.expireWrapper != null)
{
expireWrapper.Invoke();
UpdateManager.Instance.OnUpdate -= this.updateWrapper;
return;
}
}
if (updateAction != null)
{
updateAction.Invoke(dt);
}
};
UpdateManager.Instance.OnUpdate += this.updateWrapper;
this.expireWrapper = expireAction;
}
public void Reset()
{
// The timer already went off, so we need to add it back to OnUpdate
if (TotalTimeElapsed >= ExpireTime)
{
UpdateManager.Instance.OnUpdate += this.updateWrapper;
}
TotalTimeElapsed = 0f;
}
}
/* UpdateManager.cs
(c) 2017 Ritoban Roy-Chowdhury. All rights reserved
*/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Allows use of the Timer Class
/// </summary>
public class UpdateManager : MonoBehaviour
{
private static UpdateManager _instance;
public static UpdateManager Instance
{
get
{
if (_instance == null)
_instance = GameObject.FindObjectOfType<UpdateManager>();
return _instance;
}
}
public event Action<float> OnUpdate;
private void Update()
{
if (OnUpdate != null)
OnUpdate.Invoke(Time.deltaTime);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment