Skip to content

How to avoid "Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)" #17

Description

@KamilDev

I think it's needed to unsubscribe from events in OnDestroy to prevent memory leaks, such as:

private void OnDestroy()
{
    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?

Metadata

Metadata

Assignees

Labels

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions