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.
The Using Class:
In a Monobehaviour class somewhere in your project where you want to create a delayed function, do the following.