Timer.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // 2014 - Pixelnest Studio
  2. using System;
  3. using System.Collections;
  4. using UnityEngine;
  5. using UniRx;
  6. namespace KairoEngine.Core
  7. {
  8. /// <summary>Ready to use timers for coroutines</summary>
  9. public class Timer
  10. {
  11. /// <summary> Simple timer, no reference, wait and then execute something</summary>
  12. /// <param name="duration"></param>
  13. /// <param name="callback"></param>
  14. /// <returns></returns>
  15. public static IEnumerator Start(float duration, Action callback)
  16. {
  17. return Start(duration, false, callback);
  18. }
  19. /// <summary>Simple timer, no reference, wait and then execute something</summary>
  20. /// <param name="duration"></param>
  21. /// <param name="repeat"></param>
  22. /// <param name="callback"></param>
  23. /// <returns></returns>
  24. public static IEnumerator Start(float duration, bool repeat, Action callback)
  25. {
  26. do
  27. {
  28. yield return new WaitForSeconds(duration);
  29. if (callback != null)
  30. callback();
  31. } while (repeat);
  32. }
  33. public static IEnumerator StartRealtime(float time, System.Action callback)
  34. {
  35. float start = Time.realtimeSinceStartup;
  36. while (Time.realtimeSinceStartup < start + time)
  37. {
  38. yield return null;
  39. }
  40. if (callback != null) callback();
  41. }
  42. public static IEnumerator NextFrame(Action callback)
  43. {
  44. yield return new WaitForEndOfFrame();
  45. if (callback != null)
  46. callback();
  47. }
  48. public static CompositeDisposable Execute(float time, Action action)
  49. {
  50. var timer = Observable.Timer(TimeSpan.FromMilliseconds(time));
  51. CompositeDisposable cancel = new CompositeDisposable();
  52. timer.Subscribe(xs => {
  53. action();
  54. cancel.Dispose();
  55. }).AddTo(cancel);
  56. return cancel;
  57. }
  58. }
  59. }