Instantiating & Destroying GameObjects in Unity
As the game is running there are gonna be some objects that we have to create in real time like enemies, collectibles or lasers when the player is shooting. In order to do that Unity offers the method GameObject.Instantiate(), that receives as parameter the Prefab, the position in the scene and the rotation.
In this example we gonna instantiate a laser when the user press space to create a shooting action:
In the player script we have to create a GameObject variable to store the prefab, then we gonna drag the prefab from the project window and drop in the player script in the inspector:
Now within the method Update in the player script we have to use the method Input.GetKeyDown() to detect when the player press the space key, then we have to use the method Instantiate() and pass as a parameters the prefab, the position and the rotation:
Note: Quaternion is how Unity read the rotation, Quaternion.identity is the default rotation
And this is the result:
You can notice in the hierarchy we have many lasers that are already out of the screen and we don’t need any more for the game:
To solve this we gonna detect when the laser get out of the camera and remove it from the scene:
In the actual code we gonna check for the position of the laser and use the Destroy() method to remove the laser from the scene:
Now you know how to instantiate and destroy objects in Unity.