In this tutorial we’ll be covering a simple level loading system. Once you’ve reached a certain level of complexity in your game making abilities you’ll want to expand past single stage games into multiple levels. By the end of this you’ll not only to be able to switch scenes but do so in a way that is extensible and easy to maintain.
First start by opening an existing project or a fresh one and then start by creating a new empty object in the Hierarchy named Level Manager. This will be the brains of your new loading system. Create a new script of the same name and attach it to Level Manager.
Here is the script for the Level Manager, as you can see it is heavily commented. Basically the Level Manager acts as a Singleton (learn more here) that control the loading of scenes from scene to scene.
When the player hits the D key the scenes will advance using the NextLevel() method. In NextLevel() the Level Manager checks the current buildIndex with the count of scenes (important in a bit) and if it’s valid then advances otherwise it loops back to the first scene. LoadParticularScene() is just a little bonus that lets you load a particular scene by calling it’s build index. Great for setting up buttons to call a particular level like on a level select screen.
Next you’ll want to create at least two extra scenes, you can do that by either create a new scene via File > New Scene or via the Project tab by Right click > Create > Scene. Name them appropriately (I went with 1 and 2) and then give them something to differenate them from one another and your main scene with the level manager. I went with colored panels. Add them to your build settings (along with the main scene) in the order you desire.
Now’s let’s see this Level Manager go!
I’ve also set up two buttons on the Main Scene to demonstrate LoadParticularScene() as demonstration. Here’s how I set them up if you’re curious.
Here’s the Level Select buttons working as intended.
Do remember that when switching scenes that any connections made by dragging to the inspector will be broken. You will need another script (typically a UI Manager) to remake those connections when you return to the scene. This is the downside of using a singleton to carry through scenes but as long as you’re accounting for that they can be really helpful. That concludes our short tutorial on loading levels in Unity. Until next time, happy coding.