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.