Instantiating & Destroying Gameobjects in Unity
Creating and destroying gameobjects in Unity is done using the Instantiate and Destroy functions on prefabs. Here you can see capsules being instantiated from a cube at a variable distance and speed:
Later we’ll turn the cube into a space ship and the capsules will be lasers.
Here’s a link to the Unity3d docs on Instantiate:
With a prefab created and a script added to that prefab (Laser), all that is required to generate an instance of the prefab during gameplay is to reference the prefab from the player controlled object (Player) and then call the Instantiate function from the script on the player controlled game object (the cube in this case). To reference the prefab, we’ve added a variable to the Player script and then we drag the prefab onto that variable:
And here’s our instantiate reference that generates the prefabs:
We’ve set a Vector3 variable to control the spawn distance from the Player and added the Vector3 offset to the transform.position.
To add movement to the newly spawned prefab, we only need to translate the transform (transform.Translate()) in the Update method of the script on the prefab:
Spawning many prefabs and tracking them through infinity will eventually cause problems. Once the prefabs have left the screen, we want them to be destroyed. To destroy a prefab, we simply call the Destroy function from the script on the prefab: