2D Galaxy Shooter — Instantiating, Movement, and Destroying Lasers
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.
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
- Open the “Player” C# script.
- We will need to make a variable for our laser called:
“[SerializedField] private gameObject _laserPrefab”.
- 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.
- Go back to the player script and head to “Update” and add this code.
Laser Movement with a New Script
- Create a new C# script and name it “Laser”.
- Create a private float variable for speed and set it’s value at 8.0f
- Since we do not need the method “void Start()”, you can delete it.
- In Update, use the line below to have 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.
- Head back to the player script.
- Go to the if statement for instantiating the laser.
- 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!