Unity InvokeRepeating

Unity InvokeRepeating: An In-Depth Examination

Unity InvokeRepeating is a powerful mechanism that allows you to call a specific method in your class at regular intervals, with or without a delay.

We will explore its usage in detail, its advantages and disadvantages, as well as its alternatives, like my other article on “Invoke”: Unity Invoke: A Deep Dive into Method Invocation in Unity

Table of Contents

Standard Usage of InvokeRepeating

InvokeRepeating is easy to use. You specify the name of the function to call, the delay before its first call in seconds, and the interval between successive calls. If the delay is set to 0, the function is executed at the end of the current frame. Note that even if you deactivate the object after invoking InvokeRepeating, the function will continue to be called until the object is destroyed.


using UnityEngine;

public class InvokeRepeatingMonoBehaviour : MonoBehaviour
{
    private void Start()
    {
        // Call the LaunchMissile function in 3 seconds, then every 0.3 seconds
        InvokeRepeating("LaunchMissile", 3f, 0.3f);
    }

    private void LaunchMissile()
    {
        // Actions
    }
}

Improving Code Reusability

One drawback of InvokeRepeating is that it requires the function name as a string, which can be problematic when refactoring your code. A better approach is to use “nameof” from C# 6, which ensures that function renaming is handled automatically.


using UnityEngine;

public class InvokeRepeatingMonoBehaviour : MonoBehaviour
{
    private void Start()
    {
        // Call the LaunchMissile function in 3 seconds, then every 0.3 seconds
        InvokeRepeating(nameof(LaunchMissile), 3f, 0.3f);
    }

    private void LaunchMissile()
    {
        // Actions
    }
}

Cancelling an Invoke

To cancel an Invoke, you can use the “CancelInvoke” method. You have the option to cancel all Invokes or a specific Invoke using the function name or “nameof”.


private void Cancel()
{
    // Cancel all Invokes on the MonoBehaviour
    CancelInvoke();

    // Cancel only the LaunchMissile Invoke
    CancelInvoke(nameof(LaunchMissile));
}

InvokeRepeating with Parameters (Coroutine)

Unfortunately, InvokeRepeating does not allow passing arguments to the called function. For this feature, you will need to use coroutines. Coroutines offer more flexibility and allow you to manage parameters.


using System.Collections;
using UnityEngine;

public class InvokeRepeatingCoroutine : MonoBehaviour
{
    private void Start()
    {
        StartCoroutine(LaunchMissile(3f, 0.3f, 5));
    }

    private IEnumerator LaunchMissile(float delay, float interval, int number)
    {
        yield return new WaitForSeconds(delay);

        while (true)
        {
            // Perform your actions

            yield return new WaitForSeconds(interval);
        }
    }
}

Stopping a Coroutine

To stop a coroutine, it is recommended to use “StopCoroutine” by using the coroutine reference instead of the function name or “nameof”. This ensures better control over stopping coroutines.
You can also replace the while’s true with a condition.


using System.collections;
using UnityEngine;

public class InvokeRepeatingCoroutine : MonoBehaviour
{
    private Coroutine _coroutineLaunchMissile;

    private void Start()
    {
        // Store the reference in a property
        _coroutineLaunchMissile = StartCoroutine(LaunchMissile(3f, 0.3f, 5));
    }

    private IEnumerator LaunchMissile(float delay, float interval, int number)
    {
        yield return new WaitForSeconds(delay);

        while (true)
        {
            // Perform your actions

            yield return new WaitForSeconds(interval);
        }
    }

    private void StopCoroutineMissile()
    {
        // Stop all coroutines of the MonoBehaviour
        StopAllCoroutines();

        // Stop only one coroutine
        StopCoroutine(_coroutineLaunchMissile);
    }
}

InvokeRepeating vs. Coroutine

When comparing InvokeRepeating with coroutines, it’s important to note that coroutines stop when the object is deactivated or destroyed, unlike InvokeRepeating, which continues to function as long as the object exists.

Coroutines can be chained and offer a variety of yield statements to address various use cases:

For a comprehensive understanding of coroutines, please refer to Unity’s full documentation.

In conclusion, while InvokeRepeating is a functional method for invoking functions in Unity, coroutines offer better control, and a more robust approach for handling complex scenarios. Consider adopting coroutines for your Unity projects to enhance efficiency.

Leave a Reply

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