Christian Henschel
Software Engineer
How to do delayed function calls in Unity3D (one line of code)
Ok, after years of working with ActionScript 3 I got used to use Greensocks superb tweening library “TweenMax” a lot. In my opinion one of the most useful functions is the “delayedCall” method which lets me execute code with some delay (who would have guessed it).
TweenMax (AS3):
TweenMax.delayedCall(2, launchRocket);
Invoke (C#):
I was looking for a “one-liner” to do the same thing in Unity3D using C#. And I found it. It’s called “Invoke” and it’s a method of the MonoBehaviour class which all C# scripts inherit from if they are created within Unity3D.
Invoke("launchRocket", 4);
// triggers the method "launchRocket" after 4 seconds
InvokeRepeating (C#):
To do repeating calls use “InvokeRepeating” and add an additional parameter to set the delay between each call.
InvokeRepeating("launchRocket", 4, 0.5);
// triggers after 4 seconds and does another calls every 0.5 seconds
CancelInvoke (C#):
To cancel use “CancelInvoke” with the method name as parameter. If you want to cancel all invoke calls on a MonoBehaviour don’t pass any name.
CancelInvoke("launchRocket");
//cancels all invoke calls with the given method name
CancelInvoke();
//cancels all invoke calls on the current MonoBehaviour
Thank you for posting this, super helpful! Was tired of having to do a “yield wait”. This is so much easier. You rock!
Hey marc, thank you for your feedback! I’m glad this was useful to you.
Shouldn’t that second cancel be:
CancelInvoke();
???
Hey Tom, thank you. The code should now be correct.
Very useful, exactly what i needed.
I used that other method in the matual with yelding and crap, jesus it was horrible. Why is that even there when this exists.
Hey beepbeep, thank you. I stumbled across that yield/coroutine stuff myself and then found that Invoke is so much easier to use and enough in most cases. Yield & stuff is useful for other things like pulling data via http for example. (see: http://docs.unity3d.com/ScriptReference/WWW.html)
Hello from 2020. This post is still saving people like me tons of time. Just wanted to let you know. Thank you!
Hey Andrey, thanks for leaving a comment! Nice to know the post is still helping people. 🙂