Implementing a RunDelayed helper in Unity

No Such Dev
2 min readFeb 6, 2020

--

Running Delayed Logic in Unity

It is a common use case to run a piece of logic after a certain amount time in Unity. For example when a character gets a power up, it gets the buff immediately but we want to remove the buff effect after a few seconds. It would be nice to be able to write the code like this:

Implementation

There are generally two ways to go about implementing delayed execution in Unity: Coroutines and tracking time in Update() method.

Coroutines, while initially seem a bit complex with their C# specific syntax, have the nice property of separating different delayed logics into their own functions. I’ll write an in depth post about the pros and cons of each technique later. Be sure to follow me to get notifications for my newer posts. In this post, I’ll write a thin wrapper for Coroutines to give us the desired simple syntax.

Nothing out of the ordinary here. DelayedCoroutine waits for the specified time, then calls the action we passed in. The RunDelayed method is there so that we don’t have to call StartCoroutine ourselves.

Note that RunDelayed starts a Coroutine behind the scene. So we have to cancel that Coroutine if need be like any other Coroutine. We can explicitly cancel the Coroutine that is returned from RunDelayed method or stick with StopAllCoroutines .

Making it Accessible

A big problem with out current design is that we need to copy-paste those two methods to any MonoBehaviours we write if we want to use delayed logic in them. Whenever we need to copy-paste whithin our codebase, we are doing something wrong! It would be nice to have these helpers available in all our MonoBehaviours without the need to copy-paste.

Make Accessible through Inheritance

One option is to use inheritance. Create a base class that derives from MonoBehaviour and has the two additional methods. We then extend that base class in our other components.

So we can use RunDelayed in any class that extends MyMonoBehaviour .

Make Accessible through Extension Methods

The other option is to use extension methods in C#. This way we don’t need to mess with the inheritance of our classes.

Wrap up

There are pros and cons to using either technique. I personally create an extended Monobehaviour class for each project and use that throughout that project.

A sample project with all the code in this blog post is available on my github.

If you find this post useful, follow me to get more game development and Unity tutorials and learning material.

That’s it for today! Happy coding!

--

--

No Such Dev
No Such Dev

Written by No Such Dev

Software Engineer | Indie Game Developer | Founder of No Such Studio. Follow me to learn how to make video games with Unity. http://www.nosuchstudio.com

No responses yet