Skip to content

Instantly share code, notes, and snippets.

@KevinSchildhorn
Created December 29, 2018 04:43
Show Gist options
  • Save KevinSchildhorn/1013d6ad59af81f6e621b8c6e16aebf0 to your computer and use it in GitHub Desktop.
Save KevinSchildhorn/1013d6ad59af81f6e621b8c6e16aebf0 to your computer and use it in GitHub Desktop.
An alternate Timer option for Unity
int timerId = TimerHandler.ScheduleTimer(timerDelay, timerLength, repeats, (id) => {
Debug.Log("Timer Finished");
});
bool success = TimerHandler.CancelTimer(timerId);
public class TimerHandler : MonoBehaviour {
List<TimerInfo> timerList = new List<TimerInfo>();
int runningTimerIdx = 0;
void Update () {
if (timerList.Count != 0)
{
for(int i = 0; i < timerList.Count; i++)
{
TimerInfo info = timerList[i];
bool finished = info.UpdateTimer();
if (finished) {
timerList.RemoveAt(i);
}
}
}
}
// Public Static
public static int ScheduleTimer(float delayInSecs, float lengthInSecs, bool repeats, TimerDelegate del)
{
TimerHandler handler = Camera.main.GetComponent<TimerHandler>();
if (handler != null)
{
return handler.ScheduleTimerInternal(lengthInSecs,delayInSecs, repeats, del);
}
else {
Debug.LogError("Main Camera does not contain TimerHandler component");
return -1;
}
}
public static bool CancelTimer(int id)
{
TimerHandler handler = Camera.main.GetComponent<TimerHandler>();
if (handler != null)
{
return handler.CancelTimerInternal(id);
}
else
{
Debug.LogError("Main Camera does not contain TimerHandler component");
return false;
}
}
// Private
public int ScheduleTimerInternal(float lengthInSecs, float delayInSecs, bool repeats, TimerDelegate del)
{
runningTimerIdx++;
timerList.Add(new TimerInfo(runningTimerIdx, repeats, delayInSecs, lengthInSecs, del));
return runningTimerIdx;
}
private bool CancelTimerInternal(int id)
{
if (timerList.Count != 0)
{
for (int i = 0; i < timerList.Count; i++)
{
if (timerList[i].id == id) {
timerList.RemoveAt(i);
return true;
}
}
}
return false;
}
}
public class TimerInfo : MonoBehaviour {
public int id;
bool repeats;
float timerLength;
public float timeDelayRemaining;
public float timeRemaining;
public TimerDelegate timerDelegate;
public TimerInfo(int id, bool repeats, float timeDelay, float timeRemaining, TimerDelegate timerDelegate)
{
this.id = id;
this.repeats = repeats;
timerLength = timeRemaining;
timeDelayRemaining = timeDelay;
this.timeRemaining = timeRemaining;
this.timerDelegate = timerDelegate;
}
public bool UpdateTimer() {
if (timeDelayRemaining > 0)
{
timeDelayRemaining -= Time.deltaTime;
}
else
{
if (timeRemaining > 0)
{
timeRemaining -= Time.deltaTime;
}
else
{
timerDelegate(id);
if (repeats)
{
timeRemaining = timerLength;
return false;
}
else
{
return true;
}
}
}
return false;
}
}
public delegate void TimerDelegate(int timerId);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment