Declutter your Hierarchy — Spawn objects in Unity the right way!

Matej Marek
3 min readApr 9, 2021

--

Whenever you ‘Instantiate’ a GameObject into the game, it appears as an object in the ‘Hierarchy’ window. This is awesome but can become chaotic pretty fast when you start instantiating all of those prefabs!

It is always beneficial to maintain a clear and exact Hierarchy system for your GameObjects. This is because when you go about creating a game, there are constant changes to your GameObjects and to your scene - and the faster and easier you can find that one you are looking for, the better!

Let’s take a look at our Hierarchy from our previous article, where we started spawning more enemies using a Coroutine!

As you can see - the list got out of hand very quickly!

What can be done about this?

The best way is to organize your GameObjects under different compartments based on the instantiated object.

For this, we first have to create a new Empty GameObject in our scene, this will be created as a child object of our SpawnManager, and we will name it ‘EnemyContainer’ for now.

Next, whenever we use the Instantiate() in our game on our enemies, we will tell Unity to save these GameObjects under that empty GameObjects instead of directly adding them to the root level.

Now we have everything set and ready - we can first open up our ‘SpawnManager’ script. The script so far looks like this:

We will need to make some adjustments to this code.

The first edition will be a new GameObject variable, to which we will load the empty ‘EnemyContainer’ GameObject.

Next, we will have to save our instantiated object as a GameObject to a helpful variable, and then we will set its parent to our ‘_enemyContainer’ variable.

Now, we need to set the ‘EnemyContainer’ GameObject to our script on our ‘SpawnManager.’ We can set the value of this variable in our Start() method.

Alternatively, we can drag it onto the Inspector's variable space.

And that’s all it took! - since we are also similarly instantiating lasers, I will be creating a new Empty GameObject for lasers called ‘LaserContainer’ under our Player GameObject and updating the ’Player’ script as well.

And we are done! As you can see, the whole Hierarchy is now a much cleaner folder-object structure, which we can expand/close and in which we can look for our desired GameObject so much faster!

But that is it for now, thank you for reading and feel free to follow me for more articles — and as always, good luck and see you next time!

--

--

Matej Marek
Matej Marek

Written by Matej Marek

Aspiring and eager beginner Unity developer

No responses yet