Unity3D How To Delay Code Execution

Unity3D How To Delay Code Execution

In a game that I am developing, I needed a slight but simple delay of code execution in order to allow the enemy death animation to complete. Here is the method that I used:

Of the different methods to add a delay to executing code, the easiest and less complicated that I’ve found is to use the Invoke method.

There are two steps: (See the code example below)
1. Move your code to a function.
2. Invoke the function with the desired delay.

void Update() {
  // Execute the function in two seconds
  Invoke("MyDelayedCode", 2);
}

void MyDelayedCode() {
   Debug.Log("Hello!");
}

See my post about Unity3D How To Create A Simple Countdown Timer for an alternative method to create a Unity3D How To Delay Code Execution using the Time.deltatime countdown.

Unity3D has several other MonoBehaviours that perform delayed code execution but are slightly more complicated. I prefer the simple method above. However, the other more complicated methods for executing delayed code are:

  • InvokeRepeating
  • WaitForSeconds
  • WaitForSecondsRealtime
  • WaitForEndOfFrame
  • WaitForFixedUpdate

These other methods require using IEnumerator return type for the function and the yield return new which confused me early on in my Unity3D development. I have since learned and understood them but they are still unnecessarily complicated for the simple goal I was trying to achieve.

Using Invoke is easy and straightforward for any level developer to understand.

Unity3D How To Delay Code Execution