InvokeRepeating, CancelInvoke
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 22 of 63.
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
EasyThe Geyser throws the ball on top of it into the air. Its script has the ball, the power and an eruptions count. Make it erupt on a schedule:
- The first eruption comes 1 second after Play, then one every 2 seconds.
- An eruption is a method named
Erupt: it adds 1 toeruptions, pushes the ball up withball.AddForce(Vector3.up * power, ForceMode.Impulse)and logsEruption 1,Eruption 2and so on. - After the third eruption the geyser stops for good.
Press Play and watch the ball, 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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall