Unity MonoBehaviour.Invoke with C# examples

Hello programmers, In this article, you will learn about Unity MonoBehaviour.Invoke with C# examples.

Before we get started with the building process, we need to know a few concepts. Let’s first discuss them one by one.

MonoBehaviour.Invoke

The Invoke functions enable you to call a function after some specified time delay.
This allows us to build a helpful system to call methods, that is time sensitive.

Syntax: 
public void Invoke(string methodName, float time);

Example:

using UnityEngine;

public class InvokeScript : MonoBehaviour
{
    public GameObject obstacle;

    // Start is called before the first frame update
    void Start()
    {
        Invoke("SpawnObstacle", 3);
    }

    // Update is called once per frame
    void SpawnObstacle()
    {
        Instantiate(obstacle);
    }
}
  • Attach the InvokeScript to the GameObject obstacle.
  • In the Invoke Script, we can see a public GameObject named obstacle.
  • We also have a method named SpawnObstacle.
  • The SpawnObstacle method will simply Instantiate the obstacle object.
  •  As we can see in the start method, we call the Invoke function.
  • Invoke function takes two parameters.
  • The first parameter of Invoke is the name of the function that you want to execute.
  • The second parameter of Invoke is the time delay after which you want it to happen.

If we want to call Invoke method repeatedly:

To call Invoke method repeatedly can be done easily with one line of code.

Syntax: 
public void InvokeRepeating(string methodName, float time, float repeatTime);

  • InvokeRepeating function takes three parameters.
  • The third one is the repeat time.
  • The script will spawn the GameObject with the delay of repeatTime.

Example:

using UnityEngine;

public class InvokeScript : MonoBehaviour
{
    public GameObject obstacle;

    // Start is called before the first frame update
    void Start()
    {
        InvokeRepeating("SpawnObstacle", 3, 3);
    }

    // Update is called once per frame
    void SpawnObstacle()
    {
        Instantiate(obstacle);
    }
}

 

Leave a Reply

Your email address will not be published.