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
EasyMake the platform crumble a moment after the player lands on it.
- In
OnCollisionEnter, whencollision.gameObject.CompareTag("Player"), callInvoke(nameof(Fall), delay);. - Add
void Fall(): setbody.isKinematic = false;and logCrumble!.
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
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground