Menu
CoddyTech

InvokeRepeating, CancelInvoke

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 23 of 71.

InvokeRepeating(nameof(Blink), 0.5f, 0.5f) calls Blink for the first time after 0.5 seconds, then again every 0.5 seconds, until it is cancelled. The first number is the delay before the first call, the second the time between calls. CancelInvoke(nameof(Blink)) stops it, and CancelInvoke() with no name stops every Invoke the script has booked.

This warning lamp blinks until Space is pressed, then stays on:

Light lamp;

void Start()
{
    lamp = GetComponent<Light>();
    InvokeRepeating(nameof(Blink), 0.5f, 0.5f);
}

void Blink()
{
    lamp.enabled = !lamp.enabled;
}

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        CancelInvoke(nameof(Blink));
        lamp.enabled = true;
    }
}

The timer from the spawning chapter would do the same job with a float field and a check in Update(). With InvokeRepeating, Unity keeps the time and makes the calls. The call to InvokeRepeating goes in Start(): in Update() it would book one more repeating call on every frame.

challenge icon

Challenge

Easy

Make the geyser erupt three times on a schedule.

  1. In Start(), call InvokeRepeating(nameof(Erupt), 1f, 2f);.
  2. Write void Erupt(): add 1 to eruptions, call ball.AddForce(Vector3.up * power, ForceMode.Impulse); and log "Eruption " + eruptions.
  3. At the end of Erupt(), when eruptions == 3, call CancelInvoke(nameof(Erupt));.

Press Play: the ball is thrown up three times, 2 seconds apart. Then Check.

Try it yourself

using UnityEngine;

public class Geyser : MonoBehaviour
{
    public Rigidbody ball;
    public float power = 6f;
    int eruptions;

    void Start()
    {
        // Erupt 1 second after Play, then every 2 seconds
    }

    // Erupt(): count, push the ball up, log; stop after the third
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground