Instantiating and Destroying Game Objects in Unity

Jon Jenkins
2 min readMay 4, 2021

Below we see a simple game scene where a space ship fires lasers and enemies spawn on the screen:

A couple of simple questions:

1 — How do you spawn the enemies?

2 — How do you spawn the laser?

3 — How do you destroy the lasers when they are off screen or the enemies when they get shot?

The answer to those questions is by using the Unity methods Instantiate and Destroy.

Lets first talk about Instantiate.

Instantiating a new Enemy and setting its position.

We can call the Instantiate method when we want to spawn a new game object. Above, we see that we are Instantiating a new enemy prefab, at a position on screen that consists of a random x value and a fixed y and z value. We use Quaternion.identity because we aren’t concerned with the rotation.

The above example is actually 1 of many ways to instantiate. The Instantiate method has about 10 overloads, depending on what you may need. The method above is probably one of the most common and easier versions of Instantiate. As parameters, it takes a game object to instantiate, a Vector3 for the objects position, and a rotation.

Now that we’ve gotten our objects to come alive in our scene, we need to know how to destroy them when they are no longer needed. This is done with the Destroy method.

Destroy a game object that has collided with the player

When we no longer want or need an object in the scene, we can call the Destroy method as seen above. This particular line of code Destroy(gameObject) will destroy the object that the script is attached to. We can set this parameter to any game object we want though.

There is one overload for this method. The second method, Destroy(gameobject,t) allows a time to be specified before the object is destroyed.

Creating and destroying game objects in Unity is as easy as Instantiate() and Destroy().

--

--

Jon Jenkins

A Unity Developer, interested in all things Unity.