Unity3D: Instantiating and Destroying Game Objects

Gabriel Perez
3 min readMar 28, 2021
Shooting instantiated objects and destroying them when reaching out of the screen.

In Unity, instantiating game objects and destroying them will be something you’ll frequently do in your projects.

For instance, if you want to shoot projectiles from an object, you will have to instantiate the projectile game object when pressing the shoot key. And when a certain time or position is reached, it’ll destroy itself.

Let’s take a closer look at this code in the Player script.

Input logic should always be in Update().

If the Player hits the Space key within the allowed time, then Instantiate the projectile prefab.

So every time I hit the space key, the Instantiate() function is called. We pass in the game object, the position we want to spawn from, and its rotation as arguments.

The transform.position is the current position of the Player. We off-set the Y position so that the projectiles can instantiate above the Player. And Quaternion.identity means that we want the rotation to stay as-is.

The projectile prefab has a behavior of its own. Let’s take a look at its behavior.

When the projectile game object is instantiated, each instance of the projectile game object will run the code above in the Update() method.

The Destroy() function is called within a condition. If the Y position is greater than 8 on the y-axis, then destroy this projectile instance. We call in the Destroy() function and pass in the argument gameObject — Destroy(gameObject). The gameObject refers to this game object/instance. The game object the script is attached to. You can also use this.gameObject to make it explicit.

In the Scene view, we can witness the Instantiation and Destroy work together in harmony. We can also see the Hierarchy panel showing all the instances created and destroyed.

Why do we have to destroy? Good question.

It does not make sense to have our projectiles exist when they reach out of bounds from the camera. They will stay existing in 3D space! They will also congest the Hierarchy panel. And if we have thousands of instances, there’s a chance it can bog down our game.

There are other ways to optimize this. Instead of destroying the instances, we can recycle them and reuse them. The pooling system will allow you to do just that. However, that is something I will write about in the future!

Thank you for reading!

--

--

Gabriel Perez

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.