Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | 2ndGarrison |
For C#, when using delegates and events, I am wiring up objects to connect to events, and then eventually those objects are destroyed and replaced by new objects. As the game moves forward. The events are working as intended. In Ready() of the object, I attach the event handler.
CustomEvent.WasCustomTriggered += MyCustomFunction
Then I call my event, and it triggers the response and it performs as expected.
However. Later on, when the first object is disposed with QueueFree() and a new object is instantiated, when the event is triggered again, I get the below error:
System.ObjectDisposedException: Cannot access a disposed object.
For some reason, it looks like the event wired up in the disposed object’s script is still trying to execute the trigger even though it’s disposed.
My work around for this was to detach the event before disposing the object.
CustomEvent.WasCustomTriggered -= MyCustomFunction
It looks like normally, C# doesn’t require you to detach event handlers before disposing. I didn’t know if this is expected behavior or not. So my question is twofold:
- Is this expected behavior?
- If so, is there some kind of OnDestroy lifecycle method that a node calls before going into the ether that I could put cleanup code like this in?