Use Invoke methods to execute code at a given time

What if you need to invoke a specific code in 2 seconds? You can write an accumulator that counts time, use coroutine to wait for 2 seconds or simply use Invoke or InvokeRepeating methods.

Invoke

Invoke is a public method of MonoBehaviour class (so you can access it from your game scripts). It takes method name and time as parameters and it can be used in that way:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Rigidbody projectile;
    void LaunchProjectile() {
        Rigidbody instance = Instantiate(projectile);
        instance.velocity = Random.insideUnitSphere * 5;
    }
    void Start() {
        Invoke("LaunchProjectile", 2);
    }
}

This example executes LaunchProjectile method 2 seconds after starting. It’s just that simple.

InvokeRepeating

InvokeRepeating is very similar to Invoke method but it takes repeat interval as a third parameter, so there can be a difference between the first execution time and any other. Here’s an example:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Rigidbody projectile;
    void LaunchProjectile() {
        Rigidbody instance = Instantiate(projectile);
        instance.velocity = Random.insideUnitSphere * 5;
    }
    void Start() {
        InvokeRepeating("LaunchProjectile", 2, 0.3F);
    }
}

In this example LaunchProjectile method will be invoked 2 seconds after starting and then in 0.3 second intervals.

CancelInvoke

CancelInvoke allows you to cancel any pending invoke scheduled using two previous methods. It takes a scheduled method name as a parameter.

CancelInvoke("LaunchProjectile");

You may also want to check if the method is scheduled for invocation using IsInvoking method.

Possible alternatives

Invoke methods may be a nice shortcut when you want to quickly schedule a method to be invoked in the future, but it can be difficult to maintain because of passing a string as a method name. Because of that, the refactoring errors will be visible only in the run time and this usually means trouble.

Instead of using Invoke methods you may prefer to use coroutines. Coroutines are lengthy by nature, but a lot safer to maintain (of course if you’re using StartCoroutine overload that takes IEnumerator value type as parameter instead of string).

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Rigidbody projectile;
    IEnumerator WaitAndLaunchProjectile(float wait) {
        yield return new WaitForSeconds(wait);

        Rigidbody instance = Instantiate(projectile);
        instance.velocity = Random.insideUnitSphere * 5;
    }
    void Start() {
        Invoke(LaunchProjectile(2));
    }
}

 

related
IntermediateMultiplayerTutorial
Building a Turn-Based Multiplayer Game with GameSparks and Unity: Part 3
Welcome to the third part of our GameSparks tutorial series. In parts one and two we have finished...
0
GuideIntermediateTutorial
Coroutines in Unity – Encapsulating with Promises [Part 3]
  In the last part of the series we’re going to build a real example of a REST API...
5
BasicsTips
You can search your scene objects by component’s type
Did you know that besides searching your Hierarchy window by object name you can actually...
0
Call The Knights!
We are here for you.
Please contact us with regards to a Unity project below.



The Knights appreciate your decision!
Expect the first news soon!
hire us!