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

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Leverage DevOps Processes for Digital Transformation

How to Leverage DevOps Processes for Digital Transformation

Learn Binary Code

Pop-up windows, advertisements on website — what instead of them?

A new detail that helps you step up your ‘window’ game in SQL!

Flutter Stack Weekly — issue#25

Configure the Local system such that it can ping Google but cannot ping to Facebook

MY EXPERIENCE IN BOOTCAMP SO FAR

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.

More from Medium

Generating A Semi-Random 2D Platformer Level

Bullet Pools in Unity

How to Play Sound Effects in Unity

Making a 2.5D Character Controller in Unity Part 1