0
0
UnityHow-ToBeginner ยท 3 min read

How to Use Invoke in Unity: Simple Method Delays

In Unity, use Invoke to call a method after a set delay by passing the method name as a string and the delay time in seconds. This lets you schedule actions without writing timers or coroutines.
๐Ÿ“

Syntax

The Invoke method requires two parameters: the name of the method to call as a string, and the delay time in seconds as a float. The method you call must be defined in the same script and have no parameters.

  • methodName: The exact name of the method to invoke, as a string.
  • time: Delay in seconds before the method runs.
csharp
Invoke("MethodName", 2.5f);
๐Ÿ’ป

Example

This example shows a Unity script that prints a message to the console 3 seconds after the game starts using Invoke. It demonstrates how to schedule a method call without extra timers.

csharp
using UnityEngine;

public class InvokeExample : MonoBehaviour
{
    void Start()
    {
        Invoke("PrintMessage", 3f);
    }

    void PrintMessage()
    {
        Debug.Log("Hello after 3 seconds!");
    }
}
Output
Hello after 3 seconds!
โš ๏ธ

Common Pitfalls

Common mistakes when using Invoke include:

  • Passing the method name incorrectly (must be a string matching the method exactly).
  • Trying to invoke methods with parameters (Invoke only works with parameterless methods).
  • Using Invoke on methods that are private or misspelled, causing no action.
  • Not understanding that Invoke runs only once unless repeated with InvokeRepeating.
csharp
/* Wrong: Method name without quotes - causes error */
// Invoke(PrintMessage, 2f); // This is wrong

/* Correct: Method name as string */
Invoke("PrintMessage", 2f);
๐Ÿ“Š

Quick Reference

UsageDescription
Invoke("MethodName", time)Calls a method once after delay
InvokeRepeating("MethodName", time, repeatRate)Calls a method repeatedly after delay
CancelInvoke()Cancels all invokes on this script
CancelInvoke("MethodName")Cancels invoke of specific method
โœ…

Key Takeaways

Use Invoke with the method name as a string and delay time in seconds to schedule method calls.
The method called by Invoke must have no parameters and be in the same script.
Invoke runs the method once after the delay; use InvokeRepeating for repeated calls.
Always spell the method name exactly as it appears to avoid silent failures.
CancelInvoke can stop scheduled invokes if needed.