123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- // 2014 - Pixelnest Studio
- using System;
- using System.Collections;
- using UnityEngine;
- using UniRx;
- namespace KairoEngine.Core
- {
- /// <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();
- }
- /// <summary>
- /// Executes a function after a certain time has passed, based on Time.scale.
- /// </summary>
- /// <param name="time">In miliseconds</param>
- /// <param name="action">A function to be executed</param>
- /// <returns>A CompositeDisposable which can be used to cancel the timer</returns>
- public static CompositeDisposable Execute(float time, Action action)
- {
- var timer = Observable.Timer(TimeSpan.FromMilliseconds(time));
- CompositeDisposable cancel = new CompositeDisposable();
- timer.Subscribe(xs => {
- action();
- cancel.Dispose();
- }).AddTo(cancel);
- return cancel;
- }
- /// <summary>
- /// Executes a function after a certain real time has passed.
- /// </summary>
- /// <param name="time">In miliseconds</param>
- /// <param name="action">A function to be executed</param>
- /// <returns>A CompositeDisposable which can be used to cancel the timer</returns>
- public static CompositeDisposable ExecuteRealTime(float time, Action action)
- {
- var timer = Observable.Timer(TimeSpan.FromMilliseconds(time), Scheduler.MainThreadIgnoreTimeScale);
- CompositeDisposable cancel = new CompositeDisposable();
- timer.Subscribe(xs => {
- action();
- cancel.Dispose();
- }).AddTo(cancel);
- return cancel;
- }
- }
- }
|