- Home /
Optimize huge number of Destroy() calls (cannot use object pooling)
I have levels that are dynamically generated from preset tiles and objects. Each level can contain any number of any gameobjects, so object pooling doesn't work – no two levels will necessarily have the same objects.
When I switch from one level to the next, I destroy the existing level to make way for the new one. However, calling Destroy() seems to take a long time, sometimes almost ten seconds. The profiler says it may be called up to >50,000 times on one frame, as it destroys every object. Even if I just call it once on the container object the rest of level is spawned into.
Instantiating/creating levels is fast (I've optimized it) but I can't think of a way to speed up object destruction. Any ideas?
Answer by UmairEm · May 09, 2017 at 05:51 AM
@nyonge You can deactive the container by using SetActive(false); instead of destroying it. And then run a coroutine to destroy every child object every frame. This might speed things up. By the way it is always good to show a loading screen while swithing between levels.
Answer by Commoble · May 07, 2017 at 09:09 PM
If you need to destroy that many objects, it might be easier just to start a new scene for each level.
Alternatively, If you can deactivate all of your objects in a reasonable amount of time, consider just deactivating them, then giving them to a script that gradually destroys (or re-pools) the objects as time passes (e.g. destroying 100 condemned objects each frame).
Starting a new scene is impractical for my project, but deactivating objects and adding them to a "condemned" list is a great idea. Will try it out, cheers
Answer by dfeldhaus · May 09, 2017 at 05:52 AM
Some Ideas:
1) For starters, I'd pool whatever I can. So, keep the old level, generate the new level, see what overlaps, and keep it.
2) If your levels are large enough to warrant that many Destroy() calls, you might also want to consider destroying / re-using objects within the scene as you walk around. That way it'll run better anyway. If something's too far away to see or get to quickly, get rid of it and generate it when you get there.
3) There is this thing called Mesh.CombineMeshes. I've never needed to mess with it, but it might be exactly what you need. If you need the whole level at once, and it's all just static, do some texture magic and stick it all into one object, or chunks.
4) If that doesn't work, swapping out the meshes/textures between levels might. If you're using mesh colliders and you have two objects that are essentially the same except for different geometry/material, you can just swap that out.
If nothing else works, use Co-routines and a loading screen. That's pretty standard for a leveled procedural game.