Last active
October 13, 2015 21:08
-
-
Save benloong/4256567 to your computer and use it in GitHub Desktop.
Simple Timer Event Dispatcher using delegate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class TimerManager : MonoBehaviour { | |
public delegate void Callback(); | |
static TimerManager _instance = null; | |
public static TimerManager Instance { | |
get { | |
if(_instance == null) { | |
GameObject go = new GameObject("TimerManager"); | |
_instance = go.AddComponent<TimerManager>(); | |
} | |
return _instance; | |
} | |
} | |
/// <summary> | |
/// Internal Timer Object. | |
/// </summary> | |
class Timer{ | |
public string id; | |
public float interval; | |
public Callback callback; | |
public int repeatCount; | |
public Timer(string id, float interval, Callback callback, int repeatCount) { | |
this.id = id; this.interval =interval; this.callback = callback; this.repeatCount =repeatCount; | |
} | |
/// <summary> | |
/// The temp interval vary value. | |
/// </summary> | |
private float currInterval; | |
/// <summary> | |
/// Tick this instance. | |
/// return true if this timer complete, otherwise return false | |
/// </summary> | |
public bool Tick() { | |
float deltaTime = Time.deltaTime; | |
currInterval += deltaTime; | |
if(currInterval >= interval) { | |
currInterval = 0; | |
if(callback != null) | |
callback(); | |
if(repeatCount > 0) { | |
repeatCount --; | |
//if repeatCount equal 0, we need remove this timer | |
if(repeatCount == 0) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
} | |
private List<Timer> timerList = new List<Timer>(); | |
// Use this for initialization | |
void Start () { | |
} | |
// Update is called once per frame | |
void Update () { | |
completeTimers.Clear(); | |
for(int i = 0; i < timerList.Count; ++i){ | |
if(timerList[i].Tick()) { | |
timerList[i].RemoveAt(i); | |
--i; | |
} | |
} | |
} | |
public void RegisterTimer(string id, float interval, Callback callback, int repeatCount = 0) { | |
timerList.Add(new Timer(id, interval, callback, repeatCount)); | |
} | |
public void UnregisterTimer(string id) { | |
int index = -1; | |
for(int i = 0 ; i < timerList.Count; i++) { | |
if( timerList[i].id == id) { | |
index = i; | |
} | |
} | |
if(index != -1){ | |
timerList.RemoveAt(index); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment