How to create and destroy GameObjects in Unity

Jose Gil
2 min readApr 6, 2021

--

Most games will require you to create objects and destroy them, and there are many ways to do this in Unity. This article will cover how we create game objects and then destroy then when they are no longer required. This article will cover how to create a GameObject during gameplay?

Creating GameObjects in Unity

Creating a GameObject during gameplay will require you to use the Instantiate Static Method of the Object Class. Complete documentation of the Instantiate command is found here. As per this documentation, the Instantiate Static Method allows you to clone a GameObject or Component, including all children.

When a condition is met for the GameObject to be created

Instantiate(prefab, position, rotation);

The prefab is the GameObject to be created. The position is the location to create the GameObject, and the rotation is the orientation of the object.

For example let create a bullet at the location of a player with no rotation

Instantiate(_bulletPrefab, transform.position, Quaternion.identity);

Use Quaternion.identity parameter to specify that no rotation should be applied to the GameObject

In the example below, we will Instantiate a bullet from a player when the Space key is pressed.

Destroying game objects in Unity

GameObjects can be destroyed for many different reasons and conditions. Once a condition is met, you can destroy a game object by using the Destroy Static Method from within its own script;

```Destroy(this.gameObject);

You can delay the destruction by adding a time variable. (for example, a 5-sec delay)

```Destroy(this.gameObject, 5);

For more information on the Destroy Static Method click here.

Lets me know if this helps or you need further assistance with the concept of creating and destroying GameObject in gameplay.

--

--