Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Consider this some thought bubbles... use AT OWN RISK.
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- using System;
- public class MyMB : MonoBehaviour
- {
- protected Dictionary<Type, Component> cache = new Dictionary<Type, Component>();
- public T Cache<T>() where T : Component
- {
- if (cache.ContainsKey(typeof(T))) return (T)cache[typeof(T)];
- return (T)(cache[typeof(T)] = GetComponent<T>());
- }
- bool onUpdatedRunning = false;
- SortedList<Func<bool>, Action> OnUpdatedList = new SortedList<Func<bool>, Action>();
- public void OnUpdated(Func<bool> condition, Action action)
- {
- OnUpdatedList.Add(condition, action);
- if (!onUpdatedRunning) StartCoroutine(RunOnUpdated());
- onUpdatedRunning = true;
- }
- public void RunIfUpdated<T>(Func<T> getItem, Action<T> action)
- {
- T oldT = default(T);
- OnUpdated(() =>
- {
- T newT = getItem();
- if (EqualityComparer<T>.Default.Equals(newT, oldT)) return false;
- oldT = newT;
- return true;
- }, () => action(oldT));
- }
- public void RunIfUpdated<T, T2>(Func<T> getItem, Func<T2> getItem2, Action<T, T2> action)
- {
- T oldT = default(T);
- T2 oldT2 = default(T2);
- OnUpdated(() =>
- {
- T newT = getItem();
- T2 newT2 = getItem2();
- if (EqualityComparer<T>.Default.Equals(newT, oldT)
- && EqualityComparer<T2>.Default.Equals(newT2, oldT2)) return false;
- oldT = newT;
- oldT2 = newT2;
- return true;
- }, () => action(oldT, oldT2));
- }
- public IEnumerator RunOnUpdated()
- {
- while (true)
- {
- yield return null;
- foreach (var kvp in OnUpdatedList) if (kvp.Key()) kvp.Value();
- }
- }
- public void NextUpdate(Action action)
- {
- StartCoroutine(DoNextUpdate(action));
- }
- IEnumerator DoNextUpdate(Action action)
- {
- yield return null;
- yield return null;
- action();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement