Unity Fundamentals — Containers

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/

--

--

--

Unity Developer at Mooski Games

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Custom Kubernetes Deployment Template Using Monokle.

NativShark 1.0 — We’re live.

Finding elements using Appium Inspector

Projecting the Future: Remote IDEs

Streamlabs — Missing Audio on Alerts

Visual Studio for Mac’s New Integrated Terminal!

Creating your own Linux Shell

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jose Gil

Jose Gil

Unity Developer at Mooski Games

More from Medium

Pushing Objects in Unity to Complete Puzzles

Working with Unity’s 2D Tilemaps

How to Install the Universal Render Pipeline

Using Post Processing Volumes in Unity3D with the URP