I think it's needed to unsubscribe from events in OnDestroy to prevent memory leaks, such as:
privatevoidOnDestroy(){if(StatsManager.Instance!=null){StatsManager.Instance.OnStatsChanged-=OnStatsChanged;}}This works, except for when exiting play mode, sometimes it will log:
Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)
I believe it's because:
- Unity destroys
StatsManager first. - Unity next destroys the other GameObject that unsubcribes from
StatsManager event. - When checking
StatsManager.Instance != null, it causes StatsManager to respawn since StatsManager.Instance is null. (Internal Singleton behavior)
What's the best way to avoid this issue?