Skip to content

Instantly share code, notes, and snippets.

@msawangwan
Last active February 10, 2017 00:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msawangwan/bc93914c63e08a1e59ca3a0ad0c82028 to your computer and use it in GitHub Desktop.
Save msawangwan/bc93914c63e08a1e59ca3a0ad0c82028 to your computer and use it in GitHub Desktop.
[unity3d][csharp] unity helper class that caches coroutine objects to hopefully help with constantly allocating on each iteration of the routine
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// memoize shit, it's healthy
/// </summary>
namespace UnityCore {
public static class Wait {
private const string defaultCondLabel = "default cond";
private const float defaultIntervalInSeconds = 1.0f;
private static readonly WaitForEndOfFrame forEndOfFrame = new WaitForEndOfFrame();
private static readonly WaitForFixedUpdate forFixedUpdate = new WaitForFixedUpdate();
private static Dictionary<float, WaitForSeconds> intervalTable = new Dictionary<float, WaitForSeconds>();
private static Dictionary<string, WaitUntil> predicateTableWaitUntil = new Dictionary<string, WaitUntil>();
private static Dictionary<string, WaitWhile> predicateTableWaitWhile = new Dictionary<string, WaitWhile>();
static Wait() {
predicateTableWaitUntil.Add(defaultCondLabel, new WaitUntil(() => true));
predicateTableWaitWhile.Add(defaultCondLabel, new WaitWhile(() => false));
}
public static WaitForEndOfFrame ForEndOfFrame {
get {
return forEndOfFrame;
}
}
public static WaitForFixedUpdate ForFixedUpdate {
get {
return forFixedUpdate;
}
}
public static WaitForSeconds ForSeconds(float t = defaultIntervalInSeconds) {
if (!intervalTable.ContainsKey(t)) {
intervalTable.Add(t, new WaitForSeconds(t));
}
return intervalTable[t];
}
public static WaitUntil Until(string label, WaitUntil pred = null) {
if (!predicateTableWaitUntil.ContainsKey(label)) {
if (pred == null) {
return predicateTableWaitUntil[defaultCondLabel];
}
predicateTableWaitUntil.Add(label, pred);
}
return predicateTableWaitUntil[label];
}
public static WaitWhile While(string label, WaitWhile pred = null) {
if (!predicateTableWaitWhile.ContainsKey(label)) {
if (pred == null) {
return predicateTableWaitWhile[defaultCondLabel];
}
predicateTableWaitWhile.Add(label, pred);
}
return predicateTableWaitWhile[label];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment