Laser shooting… Ready, Set, Go!

Janika Suhonen
3 min readApr 8, 2021

We are using Instantiate and Destroy to shoot a laser and destroy it after the laser goes out of “boundaries”

Cube shooting

Today we will look into how we can Instantiate and Destroy an object.
This is a good way to make a shooting game or to just spawn an enemy. Can be used in many ways! :)

I used this in the 2D Shooter Game. And I will show you how it can be done easily! :) So… what are you waiting for? Let’s get to work! :)

Laser

Before we Instantiate anything we need to create our laser which we shoot :)
I created a capsule and edited the size to (0.2, 0.2, 0.2)

Capsule laser

After creating the capsule we create a “Prefabs” folder and move the capsule there. Then we can delete our capsule from the hierarchy.

Instantiate

It’s pretty simple what we need to do to instantiate an object.
We can use the pseudo-code to think about what we need to make it happen.

Pseudo-code, shoot laser

To know when the player presses the space key, we need an if statement, and inside that, we need an Input.GetKeyDown(KeyCode.Space)

So what do we put inside this if statement?
Here we Instantiate the laser Game Object.

Instantiate(Object original, Vector3 position, Quaternion rotation);

But we don’t want to instantiate the laser from our player’s position right?
We want to instantiate it from in front of the player. And that we can do by simply creating an empty game object named LaserSpawn, move it in front of the player and assign it as the player’s child object in the Hierarchy :)

Assign LaserSpawn as Players child object

After we created the LaserSpawn, the code should look like this in our if statement. We have our laser and laser spawn position.

Quaternion Identity means that the object we instantiate will be in its default rotation.

Shoot laser when pressing space

Laser Movement

We also need movement in our laser so it doesn’t just stay in one place, it would look pretty silly. :D

To make it move, we simply create a Laser script, inside the script we create private float _speed = 8.0f; variable

And in the Update make it move with transform.Translate

Make our laser move

Destroy

After shooting a laser, we don’t want it to live forever, we would otherwise have a hierarchy full of clone prefabs and that can destroy us in the long run.

To destroy the laser we add a line of code in our Laser scripts Update function just below where we make it move.

So we check, if our laser has gone further than 8f on the y-axes, we destroy it.

Destroy laser if position is greater than 8f

Amazing! Now we can shoot how much we want and we don’t need to worry about those lasers sticking in our hierarchy! :)

Thank you for reading this, I know it was a long article. So extra thanks to those who are reading this! Much love, see you in the next one!

--

--

Janika Suhonen

From the beautiful snowy country with a touch of "good" humor? Inspired Unity Developer to learn more.