Following on from my last article on creating a Spawn Manager. You will notice that if you leave the game running for a while without killing any of the spawned enemies the hierarchy will soon fill up.
All of these extra GameObjects appearing in the hierarchy can make the testing process more difficult. We can easily prevent this build up by looking at how we create our GameObjects.
The Instantiate method has several different options to consider when we use it. Taking a look at the API for the Instantiate method, we can examine those different options —
If we remind ourselves how we used this method in our Spawn Manager —
Instantiate(_enemyPrefab, spawnPos, Quaternion.identity);
Here we have called the method using the ‘_enemyPrefab’ as our Object, a Vector3 variable ‘spawnPos’ for our position and a default rotation.
We have another option very similar to this that takes an extra argument when called — a Transform. As you know, this is a component common to ALL GameObjects.
Creating a new serialized variable of type Transform, we can assign this in the inspector and add it into our Instantiate call —
private Transform _enemyParent;
Instantiate(_enemyPrefab, spawnPos, Quaternion.identity, _enemyParent);
With these changes in place, we can create a new empty GameObject in our hierarchy to house our spawning enemies —
Running our game again and letting the enemies continue to spawn, we can see that we can keep a nice clean hierarchy. If you do not need to see the enemies in the hierarchy while you’re testing, you can simply collapse them to hide the contents.