Learning Unity — Spawning Objects Without The Clutter

Joshua Nielsen
3 min readJun 11, 2021

In the last article, we learned about the purpose of Unity coroutines and how to use them. This time around, we’re going to learn how to better organize our instantiated objects. What do I mean by that? Take a look at this:

A scene in the Unity Editor — Does anything look wrong to you?

This is an example scene I have created where I have a script that can generate a “limitless” number of prefab spheres. Notice the Hierarchy window; it is completely overrun with these sphere clones. Now remember that this is a super simple example project. Imagine a real game that might have dozens or even hundreds of enemies, obstacles, pickups, etc. This could become a real mess real quick.

Fortunately, there is a very easy way to organize your scene and not be overwhelmed by objects, and that is by making use of the parent-child relationship in Unity.

To do this, we will need a new empty object to act as a container. Once you have created that, open the script you will be instantiating objects from. If you don’t have that, I have an earlier article that describes how to instantiate and destroy game objects through scripting that you can check out. Within the script variables, we will want a new reference to our object container.

Script level variables for your prefab and container

Naturally, you’ll want to give that variable the SerializeField attribute. Then within the Unity Editor, make sure to assign your container object to this new script field.

Next, back in the script, we need to put in a new line after object instantiation to put our new object into the container.

Assigning a parent to a newly instantiated game object

The Instantiate method returns a reference to the new game object created. Once we have that, we can assign a parent to the new game object. Or, more accurately, we assign it to the new game object’s transform.

Now when we are back in our game, all of our instantiated objects are assigned directly to this parent/container, keeping our Hierarchy window much more nicely organized.

All newly instantiated objects are now in the container

As you can see, this is much better! We can also have as many containers as we want as well as multiple layers of hierarchy, so organization will be a simple matter going forward.

Now that we’ve got that messy stuff sorted out, let’s explore something more visually interesting. In the next article, we are going to be looking at how to replace our 3D primitive objects with 2D sprites. Until then, good luck and happy coding!