2D Galaxy Shooter — Instantiating, Movement, and Destroying Lasers

Hello all!

Today, I’m going to explain how to instantiate a prefab laser, make the laser move up, how to destroy the laser once it leaves the screen, and how to offset the laser so it does not clip the player while moving.

Creating the laser and making it a “prefab”

When you want to make an object that you use often, like a bullet or laser in this case, you will want to make it a prefab.

Laser Prefab

First, create a primitive 3D capsule and add a red material to it. Then in your Assets folder, make a “Prefabs” folder to store your prefabs. Once that is made, drag the laser into that folder and delete the original from the Hierarchy.

Adding the “instantiate” code to the player script

  1. Open the “Player” C# script.
  2. We will need to make a variable for our laser called:
    “[SerializedField] private gameObject _laserPrefab”.
  3. Go in the inspector for our Player and look at the Script tab. Now where it says Laser Prefab with a box beside it, drag the laser from your prefabs folder into that box. This is where the script knows what to instantiate when you ask it.
  4. Go back to the player script and head to “Update” and add this code.
This is saying that if I press the Space Key, I fire the laser at my current position.
I spawn lasers now but they wont move, so lets fix that!

Laser Movement with a New Script

  1. Create a new C# script and name it “Laser”.
  2. Create a private float variable for speed and set it’s value at 8.0f
  3. Since we do not need the method “void Start()”, you can delete it.
  4. In Update, use the line below to have the laser go up.
Code you make the laser go up.

Destroying the Laser Once it Leaves the Screen

For performance, it would be best to destroy the lasers once they leave the screen using this if statement. In the Laser script, add this code ←

Fixing the Laser Offset

Now we will fix the laser so it does not clip the player when we fire.

Adding (Vector3.up * 0.8f) to the Instantiate line.
  1. Head back to the player script.
  2. Go to the if statement for instantiating the laser.
  3. Add the (Vector3.up * 0.8f) after transform.position

All that is saying is that when we fire, we fire 0.8 units above the player.

This is how to make a laser! Next, I need to slow down the fire rate.

Thank you for your time!



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
Marcus Cohee

Marcus Cohee


I am starting Unity and learning the ropes as I go! Let’s take this journey together!