Instantiating & Destroying Gameobjects in Unity

Instantiating and destroying a laser prefab


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.

The Player now spawns a laser prefab clone.

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.

code for having the laser move upwards at a reasonable speed

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.

Laser clones being destroyed after leaving the screen

Final code:

Final player code
Final laser code




Learning to become a unity game developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

My first Swift blog is about Navigation bar

CRODO VS MetaPad: Battle Of Launchpads


Make your own APNS pusher 🔔

Cert-manager additional certificate output formats config through helm

19 Reasons Exchange Online is Winning

How Much Does it Cost to Make an App

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tacoma Johnson

Tacoma Johnson

Learning to become a unity game developer

More from Medium

Instantiating & Destroying Game objects in Unity

Day 3: Layout or Get Laid Out

Unity Input System Basics

Keeping All Objects In View in Unity