Advertisement
NPSF3000

MyMB Proto 0.01

Apr 9th, 2013
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.13 KB | None | 0 0
  1. //Consider this some thought bubbles... use AT OWN RISK.
  2.  
  3. using UnityEngine;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System;
  7.  
  8. public class MyMB : MonoBehaviour
  9. {
  10.     protected Dictionary<Type, Component> cache = new Dictionary<Type, Component>();
  11.  
  12.     public T Cache<T>() where T : Component
  13.     {
  14.         if (cache.ContainsKey(typeof(T))) return (T)cache[typeof(T)];
  15.         return (T)(cache[typeof(T)] = GetComponent<T>());
  16.     }
  17.  
  18.     bool onUpdatedRunning = false;
  19.     SortedList<Func<bool>, Action> OnUpdatedList = new SortedList<Func<bool>, Action>();
  20.  
  21.     public void OnUpdated(Func<bool> condition, Action action)
  22.     {
  23.         OnUpdatedList.Add(condition, action);
  24.         if (!onUpdatedRunning) StartCoroutine(RunOnUpdated());
  25.         onUpdatedRunning = true;
  26.     }
  27.  
  28.     public void RunIfUpdated<T>(Func<T> getItem, Action<T> action)
  29.     {
  30.         T oldT = default(T);
  31.         OnUpdated(() =>
  32.         {
  33.             T newT = getItem();
  34.             if (EqualityComparer<T>.Default.Equals(newT, oldT)) return false;
  35.             oldT = newT;
  36.             return true;
  37.         }, () => action(oldT));
  38.     }
  39.  
  40.     public void RunIfUpdated<T, T2>(Func<T> getItem, Func<T2> getItem2, Action<T, T2> action)
  41.     {
  42.         T oldT = default(T);
  43.         T2 oldT2 = default(T2);
  44.         OnUpdated(() =>
  45.         {
  46.             T newT = getItem();
  47.             T2 newT2 = getItem2();
  48.             if (EqualityComparer<T>.Default.Equals(newT, oldT)
  49.                 && EqualityComparer<T2>.Default.Equals(newT2, oldT2)) return false;
  50.             oldT = newT;
  51.             oldT2 = newT2;
  52.             return true;
  53.         }, () => action(oldT, oldT2));
  54.     }
  55.  
  56.     public IEnumerator RunOnUpdated()
  57.     {
  58.         while (true)
  59.         {
  60.             yield return null;
  61.             foreach (var kvp in OnUpdatedList) if (kvp.Key()) kvp.Value();
  62.         }
  63.     }
  64.  
  65.     public void NextUpdate(Action action)
  66.     {
  67.         StartCoroutine(DoNextUpdate(action));
  68.     }
  69.  
  70.     IEnumerator DoNextUpdate(Action action)
  71.     {
  72.         yield return null;
  73.         yield return null;
  74.         action();
  75.     }
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement