Loading Scenes in Unity

Jay Barnes
3 min readNov 7, 2023

--

Now that the basic loop of our game is finished, we want to learn how to go from one leve or one scene to another and Unity makes this easy for us with the SceneManagement class.

To start, let’s say we want to restart the level after we die. We have some UI setup that tells the player to press the ‘R’ key to restart the level.

To accomplish this, first we’ll create a new empty gameobject in our scene named ‘Game_Manager’, that’ll handle everything that has to do with the state of our game, including whether the game is over or not. We’ll also create a new GameManager script and attach it to that object.

The first thing we need in this new script is a bool to determine if the game is over.

Our goal is to be able to restart the scene if we press the r key, but only IF the game is over. To do this we’ll use an if statement in Update to check if we pressed the r key AND if that _isGameOver bool is true.

if(Input.GetKeyDown(KeyCode.R) && _isGameOver == true){
//Reload Scene
}

So how do we reload the scene from here? Well, Unity has a built in SceneManagement class that gives us all the tools we need, but in order to use them we first have to add a using statement at the top of our script.

Now we can use the LoadScene function of the SceneManager class to load a specific scene. All we need is to pass in an int for the build index of the scene we wish to load. To find the build index we first have to add our scene to the build settings by going to file > build settings > and either dragging our scene from the scenes folder or pressing the ‘Add Open Scenes’ button to add the current scene we’re in.

Now that we have the build index for our scene, we can pass that in to our LoadScene() function to load or restart the scene.

With this logic, if we press the R key while the game is over, we should Load the scene at build index 0, which in our case will restart the game scene. Let’s test it out.

And that is how we use the SceneManager class to load scenes in Unity.

--

--