We're going to create a new Scene for BeginState
. As a result, we don't want the StateManager
object to be a Component of the Main Camera anymore. We'll add StateManager
to another GameObject in the new Scene. In order to do so, perform the following steps:
StateManager
Component from the Main Camera.BeginningScene
in the Scenes
folder.At this point, after clicking on Play, you will see the Press to Play button and the countdown timer in your Scene.
Add the Scenes to the Build Settings as shown in the following steps:
BeginningScene
to the Scenes In Build section.BeginState
to delete line 17, timeScale = 0;, and 43, timeScale = 1;
.By using a separate Scene while BeginState
is active, there's no longer any reason to pause the game.
In the upper right corner of Build Settings, you can see that BeginningScene is index 0 and Scene1 is index 1. If you build this project, index 0 will be loaded automatically. It doesn't work this way in the Editor. Whatever Scene is loaded runs when you click on Play.
We have two issues when using more than one Scene but both can be easily remedied:
When the game starts in BeginningScene, the GameManager is created with the StateManager
Component and BeginState
being active. When BeginState
switches to PlayState
, Scene1 will be loaded and our GameManager will be destroyed.
StateManager
Component is created.That simply isn't going to work very well. Throughout the game there needs to be only one GameManager with one StateManager
.
We want the first GameManager with its StateManager
Component to always be available. After all, it's the controller for the whole project. To prevent GameManager from being destroyed when switching from BeginningScene to Scene1, Unity provides a method called DontDestroyOnLoad()
.
We will add this in a moment, but the second issue has to be dealt with at the same time.
In our State Machine, we have LostState
switching back to BeginState
. The issue is that when BeginningScene is reloaded, another GameManager GameObject will be created. We don't want another one. We just want the first one we created when we first clicked on Play.
This is easily remedied as well by detecting that our first GameManager already exist and immediately destroying any new ones that are created.
18.118.139.224