Step 2 — Instantiate & Destroy
So now we have our moving cube. We need it to crave violence by being able to shoot lasers.

Similar to the code to move the cube, we first think of how to register a key press to do the shooting, and the key (pun intended) lies in the Input class once more, to find where the Space key is. GetKeyDown means “every time this key is pressed”.

Then we create a little Capsule 3D game object in Unity, give it another color, call it Laser, and set it up in the Inspector.


Now we call the Instantiate method, that will create this laser out of thin air!

Instantiate needs 3 arguments.
- The object you want to instantiate, the laser in our case.
- Where you want to instantiate. Since the laser comes from the player cube it’ll appear at the same location our cube is.
- Quaternion has to do with the object’s 3D rotation. As this will later be a 2D game this can be set as Quaternion.identity meaning “no rotation”.
The cube will now spawn little capsule “lasers” each time the Space key is pressed. The problem is, the lasers won’t go anywhere. They need their own script to tell them to move.
So give them a script called Laser and add the following:

Now the laser will fly up the screen after being instantiated.
You’ll note at if the laser goes beyond a y-axis value of 7f (off the screen) we call a Destroy method on the laser. This is to ensure there aren’t a billion lasers inside our game forever flying off into the ether.