I'm looking for a good way to cache an expensive function's result each frame. This code looks like it will work, but it's a bit complicated and requires deriving from MonoBehavior.
It seems like this would be needed often with Unity, since update order is unknown. Is there a better way to do it?
using UnityEngine;
using System.Collections;
public class MyClass : MonoBehaviour {
bool enableLateLateUpdate = true;
static bool myVarCachedThisFrame = false;
static float myVar;
void Start() {
StartCoroutine(LateLateUpdate());
}
public static float MyVar {
get {
if (myVarCachedThisFrame) return myVar;
//some expensive calculation:
myVar = Mathf.Sqrt(Mathf.Sqrt(Mathf.Sqrt(myVar)));
myVarCachedThisFrame = true;
return myVar;
}
}
IEnumerator LateLateUpdate() {//Coroutines update after LateUpdate. I think.
while (enableLateLateUpdate) {
MyClass.myVarCachedThisFrame = false;
yield return 0;//wait one frame
}
}
}