Spawning Objects Cleanly

Erin Kerr
3 min readOct 8, 2022
Photo by Edgar Chaparro on Unsplash

How to spawn objects in Unity and assign them to a parent object

Example of spawning objects dynamically

When you start using Unity to dynamically spawn objects, your Hierarchy can get pretty busy — especially if you are spawning the same type of object repeatedly, like the Bullet object in the example above. Instead, what if you could spawn the objects into some container, like a folder houses a set of related files?

To do this:

  • Create an empty object in your Scene to serve as a container
  • Cache a reference to the container on the script spawning the object
  • At instantiation, update the parent of the spawned object to the container

Create an empty object

Creating a BulletContainer in the Hierarchy

In your Hierarchy, right-click and select “Create Empty” to add an empty Game Object to your scene. Next, update the empty object’s name to reflect its purpose (ie. BulletContainer). Unless you have a need for the container object to exist in another position in the scene, I’d recommend updating the Transform position to (0,0,0) to avoid any unexpected behavior.

Cache a reference to the container

Create variable for the BulletContainer in Ship script

First, open the script that spawns the object repeatedly. In the example, the Ship script is spawning the Bullet objects. Next, add a new variable to the script to hold a reference to the container object and add the SerializeField attribute to access the variable in the Inspector.

Assign the BulletContainer object to the Bullet Container variable on the Ship script

Then, in the Inspector, assign the BulletContainer to the Bullet Container variable on the Ship script.

Update spawned object’s parent at instantiation

FireBullet method from the Ship script, before changes

First, you’ll need to get a reference to the newly spawned object at instantiation.

FireBullet method with a reference to the new Bullet object

To do this, create a local variable in the method that is instantiating the object (ie. newBullet). Then, assign the Instantiate call to the local variable.

FireBullet method, assigning the new Bullet’s parent to the Bullet Container

Now that you have a reference to the newly spawned object, you can update the object’s parent so it will spawn under the container object. To do this, access the newly spawn object’s parent via the transform and assign the container object’s transform to it.

Example of spawning objects dynamically to a parent object

Now, when you spawn objects in the game, they are organized under their container object — keeping the Hierarchy nice and clean!

--

--