C# Event Delegate Clean-Up

Quick Read:
After implementing events using C# Events/Delegates, I am getting this error message from Unity when ending a simulation:

Full Explanation:
I have been trying to decouple my objects in Unity/C# and have started using C# Events quite heavily.

The basic pattern goes like this:
1) Declare the event and delegate on some “manager” object:

public delegate void StateChangedEventHandler(StateEnum currentState, StateEnum lastState);
public static event StateChangedEventHandler StateChangedEvent;

2) In the Start() area of another script create delegate and subscribe to the event:

mGameStateChangedEventHandler = new GameStateScript.StateChangedEventHandler(delegate(GameStateScript.StateEnum lastState, GameStateScript.StateEnum newState)
{
   // Do some things
});
GameStateScript.StateChangedEvent += mGameStateChangedEventHandler;

3) In the OnDestroy() area of the same object that subscribed to the event, unsubscribe from the event:

GameStateScript.StateChangedEvent -= mGameStateChangedEventHandler;

This seems to all be working great. Objects clean themselves up correctly as the are destroyed, and I am not getting any more funny behavior (before I was not cleaning the subscriptions up and I was getting crashes). But I have noticed that once I added the unsubscribe code in OnDestroy() that the Unity player has problems cleaning up some of the objects and leaves dynamically created objects in the scene. Unity does give this message:

Does anyone know what I can do to prevent Unity from having this issue? I willing to add or even change how I code to avoid this.

Try unsubscribing during OnDisable() instead of OnDestroy(). If you can, subscribe during OnEnable(). Otherwise, encapsulate all subscriptions to ensure control never leaves (and an object never dies) without unsubscribing. That’s got to be what’s happening, I would think, although it does sound like what you’ve done ought to work just fine. Regarding dynamic objects not being cleaned up, do you mean GameObject objects in the scene? I’m not sure how that could be related, maybe someone else will know.

I’ve never seen this error before, but I can’t guarantee that my suggestion has anything to do with that. Manual garbage collection, what a dinosaur!

Thanks for the reply, I will try this out tonight.

Yes, I do mean the GameObject that the manager script is attached to.

i would automatically check for invalid delegates and remove them at runtime. described/linked here: http://forum.unity3d.com/threads/192741-Automatically-Remove-Event-Handlers

I was very wrong about what was causing this problem. Please see this new thread for the real problem: http://forum.unity3d.com/threads/214984-Some-objects-were-not-cleaned-up-when-closing-the-scene