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

Pulling Docker images from ECR private registries with a Cognito User Pool Identity

@madelineheising made the marshmallows & I made the…

Impersonating a service account with another service account in Google Cloud Terraform

Inter-Contract Calling in SmartPy

Linux Perf Profiling

Run a Federated GraphQL Server with Minikube

mydash101 customer care number..8081067602 any problem call now 24 hours money refund..8081067602

[Reverse Engineering Tips] — Binary Diffing

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

Overloading methods in C# & Unity

Basics of Optimization in Unity

Creating MineField In Unity (Part 1)

Unity and Variables❤