Unity Guide
Instantiating & destroying gameobjects in Unity
A quick guide to instantiate and destroy gameobjects in Unity for your game
Objective: Instantiate and destroy gameobjects in a space shooter game using Unity.
Create the laser
To continue with the space shooter game style, the player needs to generate lasers or any type of ammo to destroy enemies while avoiding collisions in the space. In order to do it, we first need to create the gameobject for the laser:
Once we have the gameobject and edited its properties we can check it in the game view or the scene view to verify if it’s appropiate:
Then, if you want, create a new material to easily identify the laser bullet in the scene:
Drag the material into the laser gameobject and the material will be attached to it:
Then, we need to create a new script and attach it as a component in the laser gameobject:
Next, create a folder for the prefabs and drag the laser gameobject from the scene to the folder to save it as a new prefab. If you want, remove the laser from the scene as it’s a prefab now and we’ll instantiate it from the player script to shoot.
Laser Behavior
Now open the laser script to modify its behavior in the scene. First, we need to have a variable for the laser speed and another for the limit of the space that the laser will travel to:
Then, in the Update function, we can assign the movement of the laser whenever it’s instantiated in the scene. For this space shooter, the laser will move towards the north:
Destroy the laser
Now to destroy the laser gameobject whenever it reaches the upper limit of the space we need to add the next condition:
If we save the script and execute the scene in the Unity editor we’ll see that the laser behavior is to go up and then get destroyed if it reaches the upper limit:
Instantiate the Laser
Now, to instantiate the laser when the player shoots in the game, we need to add a variable inside the player script (attached to it) to have a reference of the laser prefab:
Then, select the player in the scene and you’ll see the new variable for the laser prefab:
Drag the laser prefab from the prefabs folder into the script component of the player:
Return to the player script and create a new function to instantiate a laser every time it’s executed. The Instantiate function allows us to create a copy of the laser prefab in the position and rotation we choose.
Now, to instantiate the laser every time the player shoots, we need to add an input event trigger in the Update function that calls the ShootLaser function when the spacebar of the keyboard is pressed:
Now, if we execute the game in Unity, we’ll see that every time we press the spacebar a clone of the laser prefab is added to the scene and gets destroyed once it reaches the upper limit of the scene:
And that’s it, you can instantiate and destroy gameobjects with Unity! :D. I’ll see you in the next post, where I’ll be showing how to create a cooldown system for the space shooter in Unity.