Dev Day 17: Instantiating & Destroying GameObjects in Unity — Part 2

In the previous article (the link is at the end of this article), we instantiated a new Laser Prefab from the current position of the Player GameObject. Now we will look at adding movement to the Laser Prefab and then destroying it once it goes off-screen.

To start, we will create a new C# script called Laser, attach it to the Laser Prefab in the Prefabs folder, and open the Laser script in Visual Studio.

In our Laser script, we will create a private float variable for the speed the laser will move on-screen called _speed with a rate of 10.0f to start, and then add [SerializeField] so we can later adjust the private variable in the Unity Inspector window.

Next, within the Update method, we will use a similar line of code to the movement code we used for our Player GameObject, but this time our direction will only be going up on the Y-axis, so we will use Vector3.up, which we will multiply by our _speed variable, and then multiply that by Time.deltaTime.

If we save this Laser script, go back into Unity, and play our scene, we will see that the Laser Prefab now travels up on the Y-axis at a rate of 10-meters per second.

But now our Laser Prefab clones are stacking up in the Hierarchy window every time we fire a laser. The way to manage this issue is to destroy the Prefab clone once it travels outside of the screen frame. First, we will need to find the Y-axis value where we want the Laser Prefab clone to be destroyed, which for this example is Y = 8.

Once we know our Y-axis value, we can go back to our script and create an If statement within the Update method saying that if the Y-axis position of the Laser Prefab is greater than 8, we want to destroy this GameObject.

We can then save this Laser script, go back into Unity, play our scene, and we now see in the Hierarchy window that the Laser Prefab clone is destroyed right after it moves past the top of our screen.

Dev Day 16: Instantiating & Destroying GameObjects in Unity — Part 1:




Unity Developer

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

Recommended from Medium

A Green Scanner Effect with Depth Texture

Lowest Common Ancestor of a Binary Tree — Day 10(Python)

Ephemerally Yours, Part 2

Is MuleSoft good career?

Building Bluetooth Services in Zephyr

Launching WordPress and Integrate it with Amazon RDS.

Introducing Flow Mode in Qt Design Studio 1.5 — Part 1

How to use App Designer helper functions as Simulink callback methods.

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
Pete Thomasberger

Pete Thomasberger

Unity Developer

More from Medium

Cleaning up the Homing Missile code

Unity’s Tilemap System

Making Elevators In A Unity Platformer

Hidden Shortcuts to Make Level Design Easier in Unity.