daily pastebin goal
75%
SHARE
TWEET

Timer.cs

mvaganov Oct 24th, 2017 (edited) 192 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. // author: mvaganov@hotmail.com
  6. // license: Copyfree, public domain. This is free code! Great artists, steal this code!
  7. // latest version at: https://pastebin.com/raw/h61nAC3E
  8. // requires Trigger at: https://pastebin.com/raw/tMNcQbTi
  9. namespace NS {
  10.     /* // example code:
  11.     NS.Timer.setTimeout (() => {
  12.         Debug.Log("This printed 3 seconds after setTimeout was called!");
  13.     }, 3000);
  14.     */
  15.     public class Timer : Chrono {
  16.         [Tooltip("When to trigger")]
  17.         public float seconds = 1;
  18.         [Tooltip("Transform to teleport to\nSceneAsset to load a new scene\nAudioClip to play audio\nGameObject to SetActivate(true)")]
  19.         public Object whatToTrigger;
  20.         [Tooltip("If true, activate whatToTrigger when the timer triggers, otherwise, deactivate it.")]
  21.         public bool activate = true;
  22.         [Tooltip("If true, restart a timer after triggering")]
  23.         public bool repeat = false;
  24.  
  25.         private void DoTimer() {
  26.             if (repeat) {
  27.                 SetTimeout (DoTimer, (long)(seconds * 1000));
  28.             }
  29.             SetTimeout (whatToTrigger, (long)(seconds * 1000));
  30.         }
  31.  
  32.         void Start() {
  33.             base.Init ();
  34.             if(whatToTrigger != null) { DoTimer(); }
  35.         }
  36.     }
  37.  
  38.     public class Chrono : MonoBehaviour {
  39.         [System.Serializable]
  40.         public class ToDo {
  41.             public string description;
  42.             /// <summary>Unix Epoch Time Milliseconds</summary>
  43.             public long when;
  44.             public object what;
  45.             /// <summary>whether or not to Do or UNdo</summary>
  46.             public bool activate = true;
  47.             /// <summary>what could be a delegate, or an executable object, as executed by a Trigger</summary>
  48.             public ToDo(long when, object what, string description = null) {
  49.                 if (description == null) {
  50.                     if (typeof(System.Action).IsAssignableFrom(what.GetType())) {
  51.                         System.Action a = what as System.Action;
  52.                         description = a.Method.Name;
  53.                     } else {
  54.                         description = what.ToString();
  55.                     }
  56.                 }
  57.                 this.description = description; this.when = when; this.what = what;
  58.             }
  59.         }
  60.         /// <summary>using a List, which is contiguous memory, because it's faster than a liked list MOST of time, because of cache misses, and reasonable data loads</summary>
  61.         public List<ToDo> queue = new List<ToDo>();
  62.         /// <summary>The singleton</summary>
  63.         private static NS.Chrono s_instance = null;
  64.         public static Chrono Instance() {
  65.             if (s_instance == null) {
  66.                 Object[] objs = FindObjectsOfType(typeof(NS.Chrono));  // find the instance
  67.                 for (int i = 0; i < objs.Length; ++i) {
  68.                     if (objs[i].GetType () == typeof(NS.Chrono)) {
  69.                         s_instance = objs [i] as NS.Chrono; break;
  70.                     }
  71.                 }
  72.                 if(s_instance == null) { // if it doesn't exist
  73.                     GameObject g = new GameObject("<" + typeof(NS.Chrono).Name + ">");
  74.                     s_instance = g.AddComponent<NS.Chrono>(); // create one
  75.                 }
  76.             }
  77.             return s_instance;
  78.         }
  79.         /// <summary>While this is zero, use system time. As soon as time becomes perturbed, by pause or time scale, keep track of game-time. To reset time back to realtime, use SynchToRealtime()</summary>
  80.         private long alternativeTime = 0;
  81.         /// <summary>The timer counts in milliseconds, Unity measures in fractions of a second. This value reconciles fractional milliseconds.</summary>
  82.         private float leftOverTime = 0;
  83.  
  84.         public static long NowRealtime() { return System.DateTime.Now.Ticks / System.TimeSpan.TicksPerMillisecond; }
  85.  
  86.         public long Now() { return alternativeTime == 0 ? NowRealtime() : alternativeTime; }
  87.  
  88.         public static long now() { return Instance ().Now (); }
  89.  
  90.         public void SyncToRealtime() { alternativeTime = 0; }
  91.  
  92.         private int BestIndexFor(long soon) {
  93.             int index = 0;
  94.             for (index = 0; index < queue.Count; ++index) {
  95.                 if (queue [index].when > soon) break;
  96.             }
  97.             return index;
  98.         }
  99.  
  100.         /// <summary>as the JavaScript function</summary>
  101.         /// <param name="action">Action. an object to trigger, expected to be a delegate or System.Action</param>
  102.         /// <param name="delayMilliseconds">Delay milliseconds.</param>
  103.         public void SetTimeout(System.Action action, long delayMilliseconds) {
  104.             SetTimeout ((object)action, delayMilliseconds);
  105.         }
  106.         /// <summary>as the JavaScript function</summary>
  107.         /// <param name="action">Action. an object to trigger, expected to be a delegate or System.Action</param>
  108.         /// <param name="delayMilliseconds">Delay milliseconds.</param>
  109.         public void SetTimeout(object action, long delayMilliseconds) {
  110.             long soon = Now () + delayMilliseconds;
  111.             queue.Insert(BestIndexFor (soon), new ToDo(soon, action));
  112.         }
  113.  
  114.         /// <param name="action">Action. what to do</param>
  115.         /// <param name="delayMilliseconds">Delay milliseconds. in how-many-milliseconds to do it</param>
  116.         public static void setTimeout(object action, long delayMilliseconds) {
  117.             setTimeout ((object)action, delayMilliseconds);
  118.         }
  119.         /// <summary>Allows implicit conversion of lambda expressions and delegates</summary>
  120.         /// <param name="action">Action. what to do</param>
  121.         /// <param name="delayMilliseconds">Delay milliseconds. in how-many-milliseconds to do it</param>
  122.         public static void setTimeout(System.Action action, long delayMilliseconds) {
  123.             Instance ().SetTimeout (action, delayMilliseconds);
  124.         }
  125.  
  126.         void OnApplicationPause(bool paused) { if (alternativeTime == 0) { alternativeTime = Now (); } }
  127.         void OnDisable() { OnApplicationPause (true); }
  128.         void OnEnable() { OnApplicationPause (false); }
  129.  
  130.         protected void Init() {
  131.             NS.Trigger.EquateUnityEditorPauseWithApplicationPause (OnApplicationPause);
  132.         }
  133.  
  134.         void Start () {
  135.             Init ();
  136.             if (s_instance != null && s_instance != this) { throw new System.Exception ("there should only be one timer!"); }
  137.             s_instance = this;
  138.         }
  139.  
  140.         void Update () {
  141.             long now;
  142.             if (alternativeTime == 0) {
  143.                 now = Now ();
  144.                 if (UnityEngine.Time.timeScale != 1) { alternativeTime = now; }
  145.             } else {
  146.                 float deltaTimeMs = (UnityEngine.Time.deltaTime * 1000);
  147.                 long deltaTimeMsLong = (long)(deltaTimeMs + leftOverTime);
  148.                 alternativeTime += deltaTimeMsLong;
  149.                 leftOverTime = deltaTimeMs - deltaTimeMsLong;
  150.                 now = alternativeTime;
  151.             }
  152.             while (queue.Count > 0 && queue [0].when <= now) {
  153.                 ToDo todo = queue [0];
  154.                 queue.RemoveAt (0);
  155.                 NS.Trigger.DoActivateTrigger(gameObject, todo.what, gameObject, todo.activate);
  156.             }
  157.         }
  158.     }
  159. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top