Handle Death and Respawn

Handle Death and Respawn

🎯 Goal

Play effects when an object dies and bring the player back.

🧰 What You Need

  • Health

πŸͺœ Steps

Turn off Destroy On Death

On the player’s Health, turn Destroy On Death off so the object stays around after dying. It stops taking damage and healing until you reset it.

Hook On Death

Hook On Death to what should happen when the player dies: spawn an explosion with a Spawnable Effect or Health.Spawn, play a sound, and tell your game manager. On Death fires once and passes the killing blow as a DamageData.

Reset health on respawn

Hide or disable the player, wait, then call ResetHealth() and enable it again. ResetHealth() restores full health, clears the dead state and raises On Health Changed with 1.

using System.Collections;
using UnityEngine;
using GlowingRifts.ModularHealthSystem;

public class Respawner : MonoBehaviour
{
    [SerializeField] private Health _player;
    [SerializeField] private float _delay = 2f;

    private void OnEnable() => _player.OnDeath.AddListener(OnDied);
    private void OnDisable() => _player.OnDeath.RemoveListener(OnDied);

    private void OnDied(DamageData killingBlow) => StartCoroutine(Respawn());

    private IEnumerator Respawn()
    {
        _player.gameObject.SetActive(false);
        yield return new WaitForSeconds(_delay);
        _player.ResetHealth();
        _player.gameObject.SetActive(true);
    }
}

Add spawn protection

Turn on an Invincibility for a few seconds after the respawn, so the player isn’t hit straight away. See Make an Object Invincible.

πŸ“ Inspector Settings

FieldWhat it doesSet it to
Destroy On DeathDestroy the GameObject when health reaches zeroOff for players
On DeathRaised once when health reaches zero, with the killing blowEffects and your game manager

πŸ§ͺ Example

In the Many Ducks scene, DS_Player has Destroy On Death off and its On Death spawns DS_ShipExplosion. DSGameManager listens to the same event, hides the ship, waits 2 seconds, calls ResetHealth() and shows it again. The ship’s intro animation then turns on Invincibility for 3 seconds.

The ducks keep Destroy On Death on, and spawn DS_DuckDeathEffect from On Death before they’re destroyed.

πŸ’‘ Tips

  • Call Kill() to kill instantly, for example when falling out of the level. Its killing blow is DamageData.Empty.
  • Use the killing blow’s instigator to give points to whoever landed the final hit.
  • With Destroy On Death on, On Death still fires first, so effects spawned from it survive the object.

πŸ”— Related