Tutorial: checkpoints and respawning

The player goes back to the last checkpoint they touched when they fall off the world.

1. Set up

Set up
  1. Put the script on the player.
  2. Make a few checkpoints: small objects with a Trigger3D and the tag Checkpoint.
  3. Make sure there is somewhere to fall: a platform level with gaps.

2. The script

The script

Scripts/Respawn.cs

public class Respawn : Behaviour
{
    public float fallLimit = -20f;

    Vector3 safe;

    public override void Start()
    {
        safe = transform.position;
        // anything can send the player back:   Events.Emit("respawn");
        Events.On("respawn", Back);
    }

    public override void OnTriggerEnter(GameObject other)
    {
        if (!other.CompareTag("Checkpoint")) return;
        safe = other.transform.position + Vector3.up;
        other.SetColor(Color.green);
    }

    public override void Update(float deltaTime)
    {
        if (transform.position.y < fallLimit) Back();
    }

    void Back()
    {
        transform.position = safe;
        if (gameObject.rigidbody.exists) gameObject.rigidbody.velocity = Vector3.zero;
        Camera.Shake(0.2f, 0.3f);
    }

    public override void OnDestroy() { Events.Off("respawn", Back); }
}

Save it as Scripts/Respawn.cs.

3. How it works

How it works

4. Try it

Try it

Walk to a checkpoint, then jump off the edge: you return to the checkpoint, not the start.

Next: health and damage.