Loading Scenes In Unity

I’ve added another text object that appears within my GameOver function of the UI Manager script. Let’s create some functionality to reset the game.

Firstly, we can create an empty GameObject called GameManager, and have our UI Manager call a method.

In our public method, we can set a bool for is Game Over to be true.

Then within our Update method, we can use an if statement to check if the bool is true AND (&&) for the R key to be pressed. Combining the two of these conditions allows us for the R key to not reset the game unless the game is actually over.

To access our Scene Management we need to add the appropriate namespace UnityEngine.SceneManagement and we also need to add our current scene to the build. File > Build Settings allows us to add the open scene to the build.

Now within our, if statement, we can create a Scene variable to store the active scene. Getting the active scene rather than just loading a specific scene allows for better flexibility in the long run for resetting the current scene without having to change our code.

From here we can simply load the scene with our stored variables .name function.

Let’s also look at creating a different scene for the Main Menu and loading it into our game scene from there.

To do so, create a New Scene and label it accordingly. I already have a Title Screen Image within the Filebase assets. So I simply added that in, added a text component for a credit, and reused the background overlay.

To access our game scene, let’s add a button. Button UI components in Unity contain a text component and allow us to call an OnClick() function. Let’s create a UIManager for our Main Menu and assign it a new Main Menu script.

Within this script, we can create a public method to load our game. Remember to add the SceneManagement namespace and also add our Main Menu Scene to the Build Settings. On doing so, it’s good practice to reorder them so our Main Menu is Scene 0 and our Game is Scene 1.

Now within our Button component in the inspector. We need to call this method. To do so, we need to add a new function, assign the UI Manager GameObject. Then in the drop-down menu, we can find the method under MainMenu which accesses our script, then LoadGame().

Now when we press our button we can load our game scene and play!