Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A monobehaviour and extension function combination to receive a callback when a gameobject is destroyed
using System;
using UnityEngine;
public class OnDestroyCallback : MonoBehaviour {
Action onDestroy;
public static void AddOnDestroyCallback(GameObject gameObject, Action callback) {
OnDestroyCallback onDestroyCallback = gameObject.GetComponent<OnDestroyCallback>();
if (!onDestroyCallback) {
onDestroyCallback = gameObject.AddComponent<OnDestroyCallback>();
onDestroyCallback.hideFlags = HideFlags.HideAndDontSave;
onDestroyCallback.onDestroy += callback;
private void OnDestroy() {
if (onDestroy != null) {
public static class OnDestroyCallbackExtensions {
public static void AddOnDestroyCallback(this GameObject gameObject, Action callback) {
OnDestroyCallback.AddOnDestroyCallback(gameObject, callback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment