Unity C# Helpers: Delay A Function

Today I wanted to create a function which allows any other functions to be called after a specified delay. Useful for timed events.

Today’s Objective: Create a DelayedFunction function/method which calls a method automatically after a specified delay.

The Base Class:

This class simply counts down from the initial delay, calls the specified function, then disables itself to avoid executing multiple times.

To keep the code organized since only MonoBehaviours have access to Update() (which this is not), we also create a new GameObject called “Delayed Function Timer” in the scene, and add a custom component to it. This will update the timer every frame through it’s Update() method. The timer GameObject is automatically destroyed after execution to avoid garbage.

Credit to Code Monkey on YouTube for a lot of this class design

The Using Class:

In a Monobehaviour class somewhere in your project where you want to create a delayed function, do the following.

To start the timer
The code to execute after the delay has passed



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vincent Taylor

Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.