Unity Development — Spawn Cleaning
At this point, we know how to instantiate an object and we can destroy that object with collisions or some other condition. That is all great, but the reality is that there will still come a time in your games when there is a lot going on in a scene. Specifically, there may be a large number of enemies or collectibles of some kind.
Clutter in a game is ok if it is all part of your design. It can even be fun and exciting. That same clutter in your Unity Editor, however, is much less fun.
Looks like a fun little challenge, but let’s take a look at the Hierarchy in Unity now.
We can fix this with only a few lines of code in our Spawn Manager script. First, at the top of the script create a serialized GameObject variable. This will be our container for whatever we are spawning. Create an empty object in the Hierarchy and then drag this into the inspector as that container.
In your script, go to where you are instantiating the objects that are stacking up in your Hierarchy. Right before the Instantiate() call, set that new object to a local variable.
Now we have a reference to that nearly spawned object. So we can do whatever we want with it as soon as it is created. This may be obvious, but there is an actual hierarchy in the Hierarchy window. So you can set an object to be a child or a parent of another object. That is how we are going to reduce the clutter. Right after the Instantiate(), we are going to set up that container as the parent of our newly spawned object.
An object’s place in these hierarchies is based on their transform. So in code, we have to do it like this.
With that, all of the newly spawned objects will exist as children of the container. This is much cleaner in the Hierarchy.
If you want to make sure they are still there, just click that little arrow and watch the container expand.
With parenting, you’ll be able to stay organized and keep your eyes on the your goals ahead.