Adventures in GameDev with GameDevHQ! Day 27, Loading Scenes in Unity.
So we have our Game Over screen and we’re telling our player to press R to restart the game, but how do we actually do that?
At this point, it’s a good idea to have a Game Manager. A Game Manager does exactly what it sounds like, it handles and oversees what’s going on in the game and handles all the menus, inputs, and keeps track of settings for audio/video, key bindings, etc. Ours won’t be so complicated. It will only have one job. Wait for the R key to be pressed and then reset the game and we’ll do that by loading the main game scene.
Let’s create an empty and name it “Game_Manager”, we’ll also create a script called GameManager. This is such a special script that Unity even dedicates a special Gear icon to it. Don’t forget to attach the script to the empty!
Let’s load up our GameManager script and start laying down the foundation of what we’ll be doing.
This should be familiar territory by now, so our main challenge is resetting the game. We’ll be doing that by reloading the main scene, but how exactly do we do that?
Google to the rescue! And we hit the jackpot with the first link! SceneManagement is precisely what we need, let’s take a look.
And there you have it. No 10-minute youtube tutorials, no long-winded medium articles…We have the information we need right there in the first few lines of the page! So all we need to do to load a new scene is just use SceneManager.LoadScene. One caveat, it’s part of a namespace called “SceneManagement” as you can see at the left. We’re going to have to insert that namespace into our script if we want SceneManager.LoadScene to work.
Just type this at the top with the rest of the namespaces and we’ll have all the scene loading tools available to us and then nothing will stop us! NOTHING!
Ok, so what scene will we be loading anyway? Well, let’s take a look.
Normally, we'd load the Main menu, but for our intents and purposes let’s just reload the Scene that has “Game” for its name.
So let’s review: The name we use in LoadScene is the name of the scene we want to load! That wasn’t hard, was it? Ok! Let’s see it in action!
Looking good! Speaking of looking good, those are pretty cool explosions, aren’t they? We’ll be learning how to implement them tomorrow! Stay tuned!