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
| Field | What it does | Set it to |
|---|---|---|
| Destroy On Death | Destroy the GameObject when health reaches zero | Off for players |
| On Death | Raised once when health reaches zero, with the killing blow | Effects 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 isDamageData.Empty. - Use the killing blow’s
instigatorto 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.