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: https://petethomasberger.medium.com/dev-day-16-instantiating-destroying-gameobjects-in-unity-part-1-c332327962d1