Spawning Objects in Unity without the clutter

When making a game, there will always be some GameObject that you want to instantiate at runtime: enemies, power-ups, obstacles. You may notice that after a while, your Hierarchy panel with be full of GameObjects, and you will have a hard time finding something. You should keep your Hierarchy always neat.

What we could do to make our Hierarchy more organize is to make GameObject you instantiating as a child of an empty GameObject.

How to do this?

First, we need to create an empty GameObject and named it for example “Enemies”. Then, in a script that spawns enemies, we need to add a variable called “_enemyContainer”:

We add the “Enemies” GameObject in the Inspector panel.

Create a variable to store the object we just instantiated.

Now, we can set the parent of this GameObject to “_enemyContainer”.

IMPORTANT!

What you need to remember is to keep the depth of the hierarchy to a minimum. You should use a couple of small hierarchies instead of one big hierarchy.

Why?

“The reason for minimal hierarchy depth is that Unity transform system has to walk that hierarchy to notify all children when a transform changes.” — Unity

What this means is that if you have one big hierarchy, and one of the GameObject changes, all GameObjects must be notified. But if you have a couple of small hierarchies, only GameObjects that are in the same hierarchy will be notified.