Menu
CoddyTech

Invoke

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 21 of 63.

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

The Platform between the two ledges is a crumbling one. Its Rigidbody is kinematic, so it hangs in the air. Write its Crumble script:

  • When the player lands on it, it waits delay seconds (1 in the Inspector), then falls.
  • Falling is a method named Fall: it turns the platform's physics on (isKinematic = false) and logs Crumble!.
  • Before the player touches it, the platform stays where it is.

Use nameof for the method's name. Press Play and walk onto the platform with the arrows, 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!
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay