Instantiating & Destroying Gameobjects in Unity

Objective:
Have the player(cube) create a laser shot when the space key is pressed, Have the laser move upwards constantly and destroy itself when it leaves the screen.
The first thing we need to do is have the player spawn in a laser. To do this, we can use:

Instantiate will allow us when the “space” key is pressed down, the player will make a clone of the laser prefab at exactly where the player is on the screen.

It’s a good start, but now we have to give the laser prefab a script to tell the laser shot to move constantly upwards.

Now we have a working way to shoot lasers, but there is still a small problem with what happens when the laser leaves the screen:

Yes, the laser does leave the screen. However, the laser is actually still there, just moving up forever. This is not good for computer performance, and just unnecessary to keep something around that will stay forever and not be seen again. To fix this, we can use:

This destroys the laser clones as they exit the screen.

Final code:

