Spawning Objects Without Clutter in Unity

The iterative spawning of objects can be an essential part of core game loops. However, there are times in which the instantiation of such game objects outweighs the rate at which they are eliminated and will eventually lead to a cluttered Hierarchy.
Now, imagine you could neatly store your instantiated objects in a box, so…
Instead of seeing this

You would see this

We’ll be taking a look at a quick and simple way to achieve this through Object Parenting.
What is Object Parenting?
Objects in Unity follow a hierarchical structure. GameObjects may become “parents” of other GameObjects using this framework. When a GameObject has a parent, all of its transform changes are performed in perspective to that GameObject rather than the game world.
Parenting GameObjects is as simple as dragging and dropping them onto the desired parent. In the object list, a “child” object is marked by a small indentation and an arrow next to the parent object.

However, since we are dealing with instantiated objects, the parenting will be done through code.
How to create a container for your GameObjects

- Create an empty GameObject and give it an appropriate name of your choosing. This will be the container/parent of our instantiated clones.

2. Create a reference to the object in your script. You will need to access the GameObject from the script handling the instantiation.

3. Now that you have a reference to your GameObject, you can parent it through code by adding it to your Instantiation.
Your instantiation will be stored in a GameObject variable so that it can be parented using transform.parent to parent the clone container through code.

In the code sample for my Space Shooter game, this logic is being used to avoid clutter from the spawning ememies.


In the next article, I will discuss how I went from prototype to a work of art in my Space Shooter game!