Instantiating & Destroying Game Objects in Unity
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.
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.
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.