Unity: Clean up the clutter when spawning GameObjects

Instantiating many GameObjects? Tidy up your hierarchy and work more efficiently!

Timo Schmid
2 min readApr 14, 2021

You got the following objective:

The first thing we need is to create our container.
Personal recommendation: Do this inside the SpawnManager script when you have one.

As the Container is nothing more or less than a normal GameObject, we have to create a variable of type GameObject:

Next up, we need to create a reference to the Container as soon as the desired GameObject gets instantiated.
For this, we need to create a temporary variable for every instantiated GameObject.

This might be the current code for you:

Now, we need to create a temporary variable of type GameObject.
Additionally, we also need to access the transform of the created Container because the parent is stored in the transform of the temporary newEnemy variable.
This is important! Otherwise, your container will not work!

Now we have successfully assigned the Container GameObject as the parent of the instantiated GameObjects (in this case the _enemyPrefab)

Here’s a look at the finished end product:

Why you should do this:
While you probably won’t get any issues in a simple game prototype, think about creating a large project with thousands of different GameObjects. Imagine searching for the exact GameObject you need right now. Organizing and tidying up the Hierarchy with Containers will make this process more easily and enjoyable, as you have every GameObject of the same type in a separate Container.

--

--

Timo Schmid
Timo Schmid

Written by Timo Schmid

The mission? Becoming a game developer! RPG is the dream! Writing down my journey here for me and for everyone interested. Thanks for showing interest :)

No responses yet