I’m new to Unity and I would like to understand how MonoBehaviour.Invoke works under the hood.
Is this equivalent to something like this? (Except that instead of fixed “MethodToInvoke” we call an arbitrary method by its name using “GetMethod”)
public class Invoker : MonoBehaviour
{
private float invokeDelay;
private float startTime;
private bool wasInvoked;
void MyInvoke(float delay) {
startTime = Time.fixedTime;
wasInvoked = false;
invokeDelay = delay;
}
void Update() {
if (!wasInvoked && Time.fixedTime - startTime >= invokeDelay) {
MethodToInvoke();
wasInvoked = true;
}
}
void MethodToInvoke() {
// some code here
}
}
Or is there something more advanced, like a queue for methods to invoke?
Is it safe to call Invoke inside the invoked function or will it cause infinite recursion and crush my app? Something like this:
public class Example : MonoBehaviour
{
private void Start() {
Invoke("MethodToInvoke", 1f);
}
private void MethodToInvoke() {
// something useful, like spawning objects
float randomDelay = Random.Range(1f, 5f);
Invoke(MethodToInvoke, randomDelay);
}
}
I would also like to understand the bigger picture, so a deep dive on how Unity works internally will be very very appreciated!