Instantiating and Destroying Objects In Unity

Adam Reed
3 min readMar 26, 2021

--

To start this off, let's begin by explaining what “Instantiating” and “Destroying” actually mean in regards to coding in Unity.

Instantiate — This clones a game object and spawns it into the game/scene.

Destroy — To destroy something in Unity is to delete it from the game/scene.

These are two functions that are used regularly in game design! “Instantiate” can be used to spawn enemies, shoot bullets, create crafted objects, and more!

While “Destroy” can be used for things like picking up loot, removing destroyed objects/enemies from the battlefield, removing UI/Tutorial prompts that come up, or tons of other things.

To utilize the Instantiate function, there are a few different ways to go about it. The most common and easiest use is the one we will be addressing today.

At the beginning of your script, you will need to make a call reference to the prefab gameObject that you are wanting to instantiate. Then in the function seen above, simply plugin its name as well as a position and rotation that you want your prefab to spawn with, and your good!

Here I instantiate the bullet prefabs and send them moving upwards with transform.Translate!

Destroy has a number of different ways that you can go about using it in order to do a variety of things with ease.

This is with the use of…

Destroy(gameObject, 2);

which destroys the bullets after 2 seconds!

Now lastly I wanted to show you another way to use destroy that is quite useful but is a bit trickier than the last few ways I’ve shown.

So to explain this, let's start from the top. The first thing you are going to need to do is to create a reference to the parent game object that you're trying to target in your scene.

Next, you will have to input the information above but make sure you put the name of the aforementioned parent game object in the parenthesis first. The number in the parenthesis next to “GetChild” represents which game object you’re going to delete within the array of objects that the parent contains.

[Note]

When you put an object inside of another object in the Hierarchy menu in Unity, you are creating a Parent/Child object. The parent object acts like a folder and contains the child/children objects within. These children appear in an order that is actually tracked within Unity. Essentially, every parent object creates an array that can be called upon from within a script to access the specified children within.

--

--

Adam Reed
Adam Reed

Written by Adam Reed

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!

No responses yet