Spawning Objects in Unity without the Clutter
In the last article, we created a Spawn Manager that would spawn Enemy gameobjects till the end of the program, but they were cluttering the Hierarchy when generated; let’s fix that.
First, in the SpawnManager script, create a private Transform variable named “_enemyContainer” with a null value. That will be the reference of the gameobject that the enemies will be spawned as children of.
In the Instantiate after Quaternion.identity, you can add a transform that the instantiated object will be made a child of, put _enemyContainer there.
Next, create an Empty gameobject, name it “Enemy Container” and drag it into the Enemy Container field on the Spawn Manager.
Now the Enemy gameobjects that spawn are children of Enemy Container, and the Hierarchy is kept organized. The only problem now is the enemies keep spawning after the Player is destroyed.
Spot the Spawning After Player Dies
First, in the SpawnManager script, create a private bool variable named “_stopSpawning” with a false value. That is what we will use to tell the Coroutine to stop spawning enemies.
Next, in SpawnRoutine, change the while loop condition from true to _stopSpawning == false. That will cause the while loop to stop when _stopSpawning becomes true.
Now create a new method named “StopSpawning” and inside of it, set _stopSpawning to true. That will allow the Player script to change the private bool.
In the Player script, add a private SpawnManager variable named “_spawnManager” with a null value. That will hold the reference to the SpawnManager script on the Spawn Manager gameobject.
Next, to get the reference, you could serialize the private variable and drag the Spawn Manager into it, but instead, let’s use GetComponent. In the Start method, make _spawnManager equal to GameObject.Find(“Spawn Manager”).GetComponent<SpawnManager>(). That will search the scene for a gameobject with the Spawn Manager and get the SpawnManager script component. Make sure to add an if statement and null check the _spawnManager.
Finally, in the ChangeLives method, inside the if statement before the Player gameobject is destroyed, call the StopSpawning method of the _spawnManager. That will set the _stopSpawning bool to true and stop the spawning of enemies.
Now the enemies stop spawning after the Player is destroyed.
With all the game’s basic mechanics working, it is time to take it out of the prototype phase and make it look like a real game. Stay tuned for the following article, where we will do just that.