Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
KamilDev opened this issue Feb 28, 2025 · 1 comment
Assignees
Labels

Comments

@KamilDev
Copy link

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?

@hasanbayatme
Copy link
Member

I think a simple way to avoid this is to have a method to check whether there is any existing instance there without calling the get accessor on the Singleton class that initializes a new instance if there aren't any.

You could try it in your local.copy and see how it performs, like add a new method/property that just checks the internal instance field
of the singleton for null, and returns:

public bool HasInstance => instance != null;

This way, when you're unsubscribing for an event if the object is already destroyed, then no new object gets initialized by the singleton, as you're using the HasInstance in place of Instance in OnDestroy.

This should be only intended to be used in such cases as of OnDestroy or OnDisable where the instance it self could be destroyed due to Unity unloading the scene.

@hasanbayatme hasanbayatme self-assigned this Feb 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants