Created
November 8, 2017 13:14
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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