Skip to content

Instantly share code, notes, and snippets.

@PopupAsylumUK
Created November 8, 2017 13:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PopupAsylumUK/43c53390cf2cd6351657de2ed7ee8f90 to your computer and use it in GitHub Desktop.
Save PopupAsylumUK/43c53390cf2cd6351657de2ed7ee8f90 to your computer and use it in GitHub Desktop.
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) {
onDestroy();
}
}
}
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