My journey becoming a Unity game developer: Spawning objects in Unity without the clutter. Using a Spawn Manager for Galaxy Invaders pt.2
Objective: Fix the overloading of enemy clones inside the Hierarchy by using a container game object. Program it to spawn the enemies inside the container, thus keeping a cleaner looking Hierarchy and being able to locate all of the spawned enemies.
I want to use this spawning in the Update() function example from the last article. If we look inside the Hierarchy, notice the overloading of enemies spawned overwhelming the Hierarchy list. This will make it hard to impossible to check on other game objects in the Hierarchy’s list as we’re testing the game. We need to create a container, have the enemies spawn inside of it which will make it easier to locate spawned enemies, and navigate to other game objects in the Hierarchy.
Let’s begin with creating a new Empty game object inside of the Spawn Manager object and name it Enemy Container. Make sure its Transform’s positions and rotations are Reset to zeroes if it isn’t.
Back in the Spawn Manager script, create a new SerializeField Type Private Game Object name _enemyContainer which will allow us to access the actual Enemy Container game object inside it.
Inside the coroutine SpawnRoutine(), create a reference variable to the Instantiate() method with a Type Game Object name newEnemy. Then, use the newEnemy variable transform and create a new parent which will be the _enemyContainer’s transform. Remember, in order to gain access to a game object we need to do it through its Transform component.
Go to the Hierarchy and select the Spawn Manager game object. Inside the Inspector, drag the Enemy Container object into the Enemy Container slot under the Spawn Manager script component.
With the Enemy Container game object selected, play the game and see all of the enemies spawned place directly inside of the Enemy Container.