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
EasyThe 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
delayseconds (1 in the Inspector), then falls. - Falling is a method named
Fall: it turns the platform's physics on (isKinematic = false) and logsCrumble!. - 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!
}
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 Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall