Menu
CoddyTech

Invoke

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

Invoke("Explode", 3f) calls the script's own method Explode once, 3 seconds from now, and the code after it carries on at once. Unity finds the method by its name, given as a string, and the method takes no parameters. This bomb goes off 3 seconds after the game starts:

void Start()
{
    Invoke("Explode", 3f);
}

void Explode()
{
    Debug.Log("Boom");
    Destroy(gameObject);
}

Because the name is a string, the compiler cannot check it. Invoke("Explod", 3f) compiles, and 3 seconds later Unity logs Trying to Invoke method: Bomb.Explod couldn't be called. instead of exploding. C#'s nameof fixes that: nameof(Explode) is the string "Explode", made by the compiler from a name it has checked, so a typo inside it is a compile error you see before the game runs. Write Invoke(nameof(Explode), 3f);.

challenge icon

Challenge

Easy

Make the platform crumble a moment after the player lands on it.

  1. In OnCollisionEnter, when collision.gameObject.CompareTag("Player"), call Invoke(nameof(Fall), delay);.
  2. Add void Fall(): set body.isKinematic = false; and log Crumble!.

Press Play and walk onto the platform: a second later it drops. Then Check.

Try it yourself

using UnityEngine;

public class Crumble : MonoBehaviour
{
    public float delay = 1f;
    Rigidbody body;

    void Start()
    {
        body = GetComponent<Rigidbody>();
    }

    void OnCollisionEnter(Collision collision)
    {
        // When the player lands: make the platform fall delay seconds later
    }

    // Fall(): turn the platform's physics on and log Crumble!
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground