When making video games, movies, or various software, there will almost always be times that you will need to call on and load different scenes. Whether you're returning to the main menu, advancing to a new level, or simply transitioning to the next scene in a movie/cinematic, you will have to load that next scene.
So how do I do it?
Well, although the basics of this are not all that complex to use, It’s important to understand how this works and how to implement it properly. To start, we have to get a little technical.
On the top of your screen, select File>Build Settings from the drop-down window.
Now click the “Add Open Scenes” button to apply any open scenes that you have on your editor right now to the game build. This is important because otherwise, Unity would not be able to recognize the scene that you are trying to load.
Notice the numbers appearing on the far right of the scene within the “Scenes In Build” box? Well, those numbers actually represent the scenes “Build Index Number”. I’ll explain what that is used for here soon.
The “Game Manager”
When designing a video game, you will more often than not have to create what is known as a “GameManager”. A game manager can be used to track and record the various states of the game such as is the game over, do you need to load the next scene, or are there any enemies still alive. The game manager is also a great place to apply logic that checks whether the game is over and whether or not to restart it.
In this case, we will be creating an empty game object within our scene and simply naming it “GameManager”. Then we will create a script with the same name and attach it to the GameManager object.
Now for the code…
A New NameSpace Library!
At the top of your script, you will need to add a new “Name Space Library” to the default list that’s already there.
By adding the namespace “using UnityEngine.SceneManagement;” you have allowed the use of the “SceneManager.LoadScene()” behavior.
Next, you will want to add some form of a parameter to let your Game Manager know when it’s time to load your next scene. For this example, we are just going to have the user press the “R” key.
And lastly, you will need to set which scene you are wanting to load. You can do this either by “name” or by an int value known as the scenes “Build Index Number” which was explained earlier in this article.
Using the Build Index Number to identify/load the individual scenes is usually a faster and more efficient way to do it.