Instantiating & Destroying GameObjects in Unity

Renato Figueiredo
2 min readNov 29, 2023

Objective: Understand how to instantiate and destroy GameObjects in Unity .

First, in order for us to be able to Instantiate a GameObject, we need to have a reference of it, so we need to create a Prefab of that object.

How to create our Prefab.

Now that we have a copy of our GameObject, we are going to learn how to Instantiate it.

[SerializeField] private GameObject _laserPrefab;

We create a variable that is going to hold the reference of our GameObject that is going to be instantiated.

How to set our variable to our Prefab.

Now that we have a reference of our GameObject, we need to be able to Instantiate it. I’m going to set the default by pressing the Space Key.

if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(_laserPrefab, transform.position, Quaternion.identity);
}

This code above Instantiate a copy of our Prefab every time we press the space key. We have 3 parameters for our Instantiate method, which Prefab is going to be instantiated, the position of the GameObject being instantiated, and its rotation.
I’m setting as default the position that our player is currently in, and we don’t care for the rotation of the object, so we can set to Quaternion.identity to set to its default value.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response