A very simple unity timer script with co-routine is available on github. We got this unity timer script from github when we are searching some other thing then we decided to share this great stuff with you :)
sharing is caring guys!
sharing is caring guys!
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
// 2014 - Pixelnest Studio | |
using System; | |
using System.Collections; | |
using UnityEngine; | |
/// <summary> | |
/// Ready to use timers for coroutines | |
/// </summary> | |
/// <summary> | |
/// Ready to use timers for coroutines | |
/// </summary> | |
public class Timer | |
{ | |
/// <summary> | |
/// Simple timer, no reference, wait and then execute something | |
/// </summary> | |
/// <param name="duration"></param> | |
/// <param name="callback"></param> | |
/// <returns></returns> | |
public static IEnumerator Start(float duration, Action callback) | |
{ | |
return Start(duration, false, callback); | |
} | |
/// <summary> | |
/// Simple timer, no reference, wait and then execute something | |
/// </summary> | |
/// <param name="duration"></param> | |
/// <param name="repeat"></param> | |
/// <param name="callback"></param> | |
/// <returns></returns> | |
public static IEnumerator Start(float duration, bool repeat, Action callback) | |
{ | |
do | |
{ | |
yield return new WaitForSeconds(duration); | |
if (callback != null) | |
callback(); | |
} while (repeat); | |
} | |
public static IEnumerator StartRealtime(float time, System.Action callback) | |
{ | |
float start = Time.realtimeSinceStartup; | |
while (Time.realtimeSinceStartup < start + time) | |
{ | |
yield return null; | |
} | |
if (callback != null) callback(); | |
} | |
public static IEnumerator NextFrame(Action callback) | |
{ | |
yield return new WaitForEndOfFrame(); | |
if (callback != null) | |
callback(); | |
} | |
} |
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
const float duration = 3f; | |
// Simple creation: can't be stopped even if lopping | |
//-------------------------------------------- | |
StartCoroutine(Timer.Start(duration, true, () => | |
{ | |
// Do something at the end of the 3 seconds (duration) | |
//... | |
})); | |
// Launch the timer | |
StartCoroutine(t.Start()); | |
// Ask to stop it next frame | |
t.Stop(); | |
Comments
Post a Comment