Hello people,
I’ve been restarting the main game scene (the playing scene) on GUI button click and wroks. Although there is one problem, it takes around forever to reload the scene.
Then I tried with Application.LoadLevel(Application.loadedLevel) and it kind of reloaded a little bit faster, just a little. Although it still takes like 10 seconds to reload (and longer if I played the game for a longer period), even though my game is veeery simple, it is not that heavy. I also noticed that the player score still displays and I need to reset it when the restart button is clicked (when using Application.LoadLevel).
Is there actually any best practice to restart a game scene without it taking that long to reload?
Thanks a lot!
As with all other load times, the biggest performance gain you’ll get is usually to stop destroying and creating so many objects (which may seem odd at first, since your goal is to destroy and recreate the scene). You may want to look into object pooling and DontDestroyOnLoad. The premise is that instead of using the scene to instantiate all of your objects, you instead instantiate the common ones into pools immediately, and any managers in your scene that actually needs them can request them from the pool. For instance, enemies, buildings, possibly terrain objects like rocks and trees, projectiles, skill special effects, etc…
At the extreme end, object pooling can be used with occlusion and frustum culling so that when scene objects are out of sight, they effectively (graphically, at least) cease to exist. Their model entities are returned to the pool, and then can be freely taken out and used again by other objects as they need to be drawn on screen and cut down on loading duplicate assets as much as possible. You don’t have to get that complex though- usually it’s just a matter of “when an object would otherwise need to be instantiated and loaded into the scene, pull it from a pool of pre-generated objects instead” and “when an object would otherwise need to be destroyed, clean off the changes that have been made to it and insert it back into the pool instead”.
By using this concept with DontDestroyOnLoad, and then running a process before changing scenes / reloading the game that tells all scene objects to re-pool themselves if possible, you’ll be able to cut down on the number of objects you actually need to instantiate again immensely. As instantiating and destroying GameObjects is usually the heaviest task Unity has to perform, this will likely have a massive effect on your load times, though the degree and scope of which you can pool your scene objects depend a lot on they way that you’ve constructed them too.