Unity Fundamentals — Containers

Jose Gil
3 min readApr 12, 2021

--

You will have situations where your Hierarchy will become cluttered with spawned objects. This will make debugging much more difficult, especially if you are spawning different types of GameObjects.

Instantiating GameObjects will be automatically be added to the root of the Hierarchy. Eventually, you will have too many GameObject to manage, so we need to organise them. Let me introduce Containers; the way to organise your GameObjects.

Containers

Containers are empty GameObjects that we Instantiate a GameObject within. At Mooski Games, we use Containers for different types of GameObjects like enemies, power-ups and more.

Let’s get organised

From my previous article on Coroutines, we used a SpawnManager GameObject and an associated script. However, all of the enemies we spawned ended up in the Hierarchy.

To create a Container, we create an empty GameObject, rename it appropriately and then drag it to the parent container. In our example, we created a container called EnemyContainer and dragged it to the SpawnManager

Within the SpawnManger script, we need to create a GameObject for the Container. We SerializeField the variable so we can assign the Container to it within the Inspector.

[SerializeField]
private GameObject _enemyContainer;

We now drag the EnemyContainer GameObject to the SpawnManager’s Script variable within the Inspector.

Now we need to change how we Instantiate the GameObjects. To be able to affect an Instantiated GameObject, we assign it to a GameObject variable.

GameObject enemy = Instantiate(_enemyPrefab, new Vector3(Random.Range(-2.3f, 2.3f), 8, 0), Quaternion.identity);

Finally, we assign the Instantiated GameObject into the new EnemyContainer Container by changing its parent.

enemy.transform.parent = _enemyContainer.transform;

Now we are organised

Hopefully, this article has helped you organise your Hierarchy, and you have been able to successfully implement containers in your projects. Check out my other articles here — https://jose-gil.medium.com/

--

--