A simple, generic way to execute delayed code with coroutines in Unity

Quite often a chunk of code must be executed one or more frame ahead, sometimes because it’s just convenient to do so, other times because your code simply wouldn’t work otherwise.

Unity exposes a very handy type called UnityAction to deal with delegates on the fly. You almost don’t need any knowledge about delegates to use this approach, nonetheless I suggest you have a look to C# delegates anyway.

The method that does the job is embarrassigly simple.

Now the way to use it might seem a bit strange if you never wrote an anonymous method. In C# anonymous methods are considered as delegates so we will use an anonymous method to pass any code to our delayedAction.

And that’s all you have to do to execute any code after waiting for the next frame.

Of course you can bend the delayedAction method to your needs. For example you might want to use WaitForSeconds instead of WaitForEndOfFrame, or you might want to wait for n frames before Unity executes the delayed code. In that case:

which would now be called as follows: