Instantiating & Destroying Game Objects in Unity

Rob George
2 min readMar 31, 2021

Day 4 — Aspiring Game Creator

2D Game Dev: Galaxy Shooter

INSTANTIATE

Instantiate is Unity’s function to create clones from prefabs.

Prefabs are simply game objects which have been transformed into a prefab.

In this example, the spaceship will instantiate clones of the laser prefab whenever the space bar is pressed.

In order to give the illusion that the spaceship is actually firing a laser from the tip of the laser cannon an ‘invisible’ game object, FireLeft and FireRight (we’re firing two laser beams), are added to the tips of each laser cannon game object. Below those game objects are assigned to the _gunLeft & gunRight variables:

The Instantiate function uses three variables: prefab, position & rotation.

FireRight & FireLeft objects, colored red for this example, are the instantiation points for the Laser prefab.
The Spaceship INSTANTIATES the laser prefab whenever the FireLaser function is called.

DESTROY

Once the laser game objects move beyond a particular vertical threshold they are no longer necessary so they should be destroyed.

Destroying any game object in Unity is fairly easily, simply make a call to the destroy function.

The laser game objects are destroyed when their vertical coordinate is equal to 8.0f.

In the above example, to highlight the Destroy method, a vertical threshold bar has been placed at Y = 8.5f, just above the yThreshold variable.

The lasers will vanish just below the red bar.

--

--