- Home /
Do events need to be manually un-allocated before destruction?
I'm working on using events to set up a cursory observer pattern, and let's say I do something like the following:
public delegate void SomeNotification(GameObject invokingObject, ObserverEvent eventEnum);
public class SubjectClass : MonoBehaviour
{
public event SomeNotification testNotification;
}
public class ObservingClass : MonoBehaviour {
SubjectClass testSubject;
public void OnNotify(GameObject invokingObject, ObserverEvent eventEnum)
{
}
void Awake()
{
testSubject = new SubjectClass();
testSubject.testNotification += OnNotify;
Destroy(testSubject);
}
}
I'll never get a null reference, because SubjectClass was the one subscribed to ObservingClass's OnNotify, not vice-versa. However, I never explicitly un-subscribed testNotification from the things it was talking to before destroying its object. Can I trust Unity to clean this up after the Destroy call, or have I just created an inadvertent memory leak by deleting SubjectClass before calling testNotification -=OnNotify?
Answer by Hanoble · Jul 29, 2017 at 09:25 AM
Without manually unsubscribing you still have a reference and it will not be garbage collected. A common technique is to use the OnDestroy() of the listening class to unsubscribe, or just explicitly do it before calling destroy.
Right, that means the answer is "Yes". A managed object actually can't be destroyed. Unity's Destroy method only destroys the native C++ part of the class. The managed part will be removed by the GC once all referenced to that class go out of extent.
$$anonymous$$onoBehaviour derived classes must not be created with "new". If the class should be a component you have to use AddComponent to create an instance dynamically.
ps: technically it's not a "memory leak" by definition since it's possible to retrieve the reference stored in the multicast delegate using reflection. A memory leak is only a memory leak if there's no way from inside the application to free the memory. Also if "SubjectClass" is destroyed and finally garbage collected all classes refered by the delegate are collected as well if that was the last reference to those classes.
Your answer

Follow this Question
Related Questions
m_Memory.renderTextureBytes<0 1 Answer
Memory Leak Help 2 Answers
Object references listed in profiler but not in hierarchy. 1 Answer
Memory leak when running Process() 0 Answers