Spawning Objects in Unity without the Clutter!

Michel Besnard
3 min readJun 3, 2021

--

Objective: Keep the Hierarchy clean and free of clutter when spawning GameObjects.

What you want is for the cloned GameObjects to be instantiated as children of an empty container within the Spawn Manager. So, how could we do this?

Step 1 — instantiate the object

Step 2 — get a reference to that object

Step 3 — assign the parent of the object to the Spawn Manager or whatever the container is.

Inside the Spawn Manager, create an empty object, rename empty object as “Enemy Container”. This is where you will place all of your enemy game objects so they don’t clutter up the hierarchy.

Add a [SerializeField] private GameObject _enemyContainer to the SpawnManager script in order for the Spawn Manager to know about this empty container. Save the script and head back into the Inspector to assign the EnemyContainer gameobject to the empty field. Once that is done, we have access to this empty container into which we can store the spawned game objects.

In order to hold a reference to the newly instantiated object, we need to store that new object into a GameObject type variable. In this case, we instantiate the _enemyPrefab at a random position along the X-axis, and store it into newEnemy.

Once this GameObject newEnemy has been created, we can access (get) the parent of the newly instantiated object, and reassign (set) its parent to the Enemy Container game object transform.

Now, when we spawn a new enemy game object, it will become a child of the Enemy Container.

Complete IEnumerator coroutine sending enemy game object into the Enemy Container.
Instantiated objects appear as children of the empty game object “Enemy Container”, therefore keeping the Hierarchy tidy!

--

--

Michel Besnard
Michel Besnard

Written by Michel Besnard

Military member with 35+ years of service, undertaking an apprenticeship with GameDevHQ with the objective of developing solid software engineering skills.

No responses yet