// 2014 - Pixelnest Studio using System; using System.Collections; using UnityEngine; using UniRx; namespace KairoEngine.Core { /// Ready to use timers for coroutines public class Timer { /// Simple timer, no reference, wait and then execute something /// /// /// public static IEnumerator Start(float duration, Action callback) { return Start(duration, false, callback); } /// Simple timer, no reference, wait and then execute something /// /// /// /// 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(); } /// /// Executes a function after a certain time has passed, based on Time.scale. /// /// In miliseconds /// A function to be executed /// A CompositeDisposable which can be used to cancel the timer 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; } /// /// Executes a function after a certain real time has passed. /// /// In miliseconds /// A function to be executed /// A CompositeDisposable which can be used to cancel the timer 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; } } }