A Tidy House is a Happy House….
Spawning Objects in Unity without the Clutter
Yesterday, we looked at using coroutines to continuously spawn enemies over time. Having a continuous stream of things to shoot is fantastic for our player but the result in our Unity editor can get quite messy over time! Today we are going to clean up our hierarchy and place all those spawned objects into a container object!
First we’ll create our container object by right clicking in the hierarchy window and selecting “Empty Object”. Then we’ll name our object “Enemy Container”.
Now that we have a place for enemies to spawn we need to specify for them to spawn there.
Unity’s Instantiate method has a 4th, optional parameter that allows you to specify the parent object of the object you are instantiating. We can use this to specify the container for our enemy objects to spawn in. First we need to create a variable for our enemy container object so that we can assign it in our instantiating code.
Now that we have access to the container, we can include it in the Instantiate call like so
Note that the signature for this overload of Instantiate calls for a Transform object, so I passed in the containers Transform. I could have just as easily made our serialized field of type Transform. I personally prefer to use GameObject where I can instead of Transform. It makes more sense in my head when thinking through my code.
Now as our enemies spawn in they will spawn in under our container!
There we are! We have cleaned up our hierarchy and our enemy objects now spawn under a parent container. Tomorrow, we take a look at moving from our primitive prototype to a version with graphics! If you enjoyed this article, or want to come along with me as I progress on my journey, follow me at gamedevchris.medium.com.