Spawning countless Game Objects can become problematic when it comes to keeping your game and hierarchy well organized. The image below shows how the hierarchy looks after spawning a few enemies. It doesn’t look too chaotic and that is because my game is in the early stages with only a few Game Objects being used. But, imagine any published game and the amount of Game Objects that are being used, and after running the game for a few seconds, starts filling up with prefabs…it would be chaos! If there is one thing my parents taught me it is to keep a clean and kept room and I am assuming they also meant game hierarchy.
The image below is showing an organizational method of creating an empty Game Object that will hold all of the spawning Game Objects. In my case, there is an empty Game Object called Enemy Container and it will simply hold all of the spawning Enemy prefabs. Instead of them just popping up in the hierarchy, cluttering up the whole thing, they have a nice sport where they will live. Unfortunately, it is not as simple as dragging and dropping the Enemy Clones into the Enemy Container. We need to tell the Enemy Clones, when they spawn, they will spawn as a child of the Enemy Container.
This is happening all inside of the Spawn Manager, so we will need to add the _enemyPrefab and _enemyContainer to the script.
Since, we added the_enemyPrefab and _enemyContainer to the Spawner Manager script we have access to them. So, every time we Instantiate (create) a new enemy it will be store inside the local variable newEnemy. Once the clone of the Enemy is store in the variable we just need to assign its transform to the parent Game Object, which is the Enemy Container, making it now a child of that Game Object. This method is going to come in handy when adding Power Ups and Enemy Fire to my game and truly help keeping my game neat and organized.