Game Development Reference
In-Depth Information
The most important thing to understand about DontDestroyOnLoad is that it will happily add duplicate
gameObjects every time a scene is restarted. In this game, if for instance, you told the Gnomatic
Garden Defender to DontDestroyOnLoad every time you went out to the Main menu and came back, a
new Gnomatic Garden Defender would be created. Let's try a quick test.
1.
Open the GardenLevel1 scene.
2.
Create a new C# Script in the Game Scripts folder, and name it
LevelManager .
3.
Add the following code to it:
void Awake () {
DontDestroyOnLoad (transform.gameObject);
}
The DontDestroyOnLoad code is always put in an Awake function, so it is one of the first commands to
be read.
4.
Save the script, and drop it on the Gnomatic Garden Defender.
5.
Click Play, and go back and forth from the Main Menu and watch the
Hierarchy view (Figure 10-40 ).
Figure 10-40. The Gnomatic Garden Defender duplicate problem
6.
Stop Play mode, and remove the Level Manager component from the
Gnomatic Garden Defender.
 
Search WWH ::




Custom Search