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.

A large number of obstacles on the screen

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.

This could be very fun

Looks like a fun little challenge, but let’s take a look at the Hierarchy in Unity now.

This is less fun

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.

Our local GameObject variable sets the container as its parent

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.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Let’s put an end to bad drops on Solana!

WordPress Installation Made Easy

Cookies, what are they? Who are they? And what do they know?

REST API with SpringBoot (Kotlin / Java)

*How To Read Ram in Linux*

The Objetives and Buildup of API3

What Is a Cloud Digital Asset Management (DAM) System?


Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Christopher Graf

Christopher Graf

More from Medium

Making a RTS game #37: Using workers to construct buildings 2/3 (Unity/C#)

Journal 144 — Unity Project Development, 2.5D Shooter

Creating Enemy Explosions

Attack while jumping