Instantiating and destroying objects in Unity

Let’s talk about “lasers.” Dr. Evil wanted to use one to rip a hole in the ozone-layer, but we’re going to use one as the projectile in our space shooter game. Today we’re going to be looking at how to instantiate and destroy our projectiles.

Instantiating an object basically means you are creating a new instance of it. Typically in Unity, you will be instantiating objects from a prefab, which I’ve already created. The logic for firing projectiles will be handled in the player script, and I will use the space-button to fire. Like before, I’m referencing the built-in Unity Input class to read input. Here is the code handling the projectile in the player script.

I’m checking for the space-button to be pressed each frame and if the reload time is up. If it is, I call the ShootLaser method which will set the new reload time and instantiate an instance of the laser prefab. I added an offset value to the y-position where it instantiates so that the laser appears to spawn in front of the player object. Now that the laser is instantiated, it needs some logic added so that it flies upward. I created a laser script and attached it to the laser prefab.

I’m using the Translate function in the update method to move the projectile upwards, and am giving it a speed value of 8. I added the Destroy call to the start method with a timer so that the laser objects are deleted after being alive for 3 seconds. This time can change in the future. Check it out!