- Home /
Garbage collection and cleanup when Scene unloads
What are some good practices when unloading a Scene in terms of garbage collection? Should this code be put in an OnDestroy method or?
I am using no EventDispatchers but I am creating a new gameObject based Dictionary every time my Scene loads. (called from Start())
Answer by Shadex · Apr 11, 2021 at 08:03 AM
Garbage collection happens when you unload a scene. If you want to call it manually use System.GC.Collect();
Generally the strategy is to split up a level in chunks, and load the chunks as needed. know that there is a small spike when GC is called. This means keeping everything the same size, or to have predictable points when your calling GC, so you can hide the spikes. Doors are wonderful at this.
No clue what your talking about creating a new gameObject, but that gets GC when the scene it's instantiated in gets unloaded like everything else. Typically it's good practice to protect some gameObjects like the player, inventory system or other persistent things with Don't destroy on load. The main thing you want to GC 9/10 times is going to be textures. One trick is to load heavily textured prefabs into there own scene to help control texture load.
Hope this helps @eco_bach
Your answer
Follow this Question
Related Questions
Prevent 'Cleaning up leaked objects' 1 Answer
How can I modify a Mesh object's uv variable directly? 1 Answer
CPU being choked by GC.MarkDependencies 1 Answer
Native Mesh Access 1 Answer