Use Invoke methods to execute code at a given time

Facebooktwittergoogle_plusredditpinterestlinkedinmail

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:

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:

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.

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).

 

One thought on “Use Invoke methods to execute code at a given time

  1. I would print the part about Invoke() taking a string in bold, red letters personally. It’s not compile-time recognized, it’s heavier to execute, it slips by all refactoring tools in any IDE, prone to writing errors etc etc.

    While Coroutines also generate a bit of garbage, they can be conventiently encapsulated. Just create a singleton monobehaviour with

    public static Coroutine Invoke(IEnumerator enumerator, float delaySeconds)

    That way you can just call a one-liner like with Invoke(), but with all the benefits of Coroutines (e.g. safety, you can cancel *one specific* instance of the Coroutine, instead of cancelling all).

Leave a Reply

Your email address will not be published. Required fields are marked *