Programming, Work

Scene management in Unity

When you are creating various scenes in Unity, you tend to populate it with all the items you need to test it with. Cameras, players and everything that makes sense for testing. As soon as you start transitioning between those scenes, you start having problems because objects are being destroyed and recreated. You need to hold on to some sort of object state or prevent some objects form being destroyed on load.

There is actually a very simple solutions to this.

You create a base scene for your camera, menu item and main items that you know will travel between the scenes and mark all of those as not destroyed on load. When you start the game, make sure it starts with this base scene and loads any target scene from there. This way any new scene is just added to this framework and you don’t really need to worry too much about object management when transitioning between scenes in Unity. Any item you pick up from the other scenes you just mark as don’t destroy on load as you travel between the scenes and everyone is happy. No need to persist a lot of things as you transition, since all the state is still there in the base scene to begin with.

You could create some simple framework around this and prefabs so that you can easily drop this into any scene you are creating to test it of the bat, but when actually are running the game and solving various things you need to make sure the objects that need to be destroyed are destroyed and the ones that need to stay active are not torn down.

So, in short, create this little scene and store the current scene index most likely on the Game Controller for loading.

 – GameController
– MainCamera
– Player
– UI

From this scene you either load the other scenes additively or just make sure all these game objects are marked as don’t destroy on load. The additive solutions might be a little heavy on the memory since it just adds more and more things to your scene, so the alternate solutions would be better.

Just some morning thoughts for you game programmers.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s