Perfectly Balanced: Destroying Game Objects in Unity
In my previous post I wrote about Instantiating or creating a Laser Prefab that when fired would continue traveling up the screen for as long as time.
With all of these Laser Prefabs being created it would eventually slow down the game, so we must find a balance by allowing the Laser Prefab to be create, travel up the screen until it is out of the game view then destroy it. In this, we will find the game performance to be…
The Instantiation of the Laser Prefab is on the Player Script because the Laser will be spawning from the Player when the Space Bar is pressed. After that, the Laser is its own Game Object with its own behavior so it will require a Script to handle the Laser after it has been created.
First, we are moving the Laser up the screen by Translating it with the Vector3.up shortcut and multiplying it by a [SerializeField] speed variable (so it can be adjusted in the Inspector) and Time.deltaTime to give us speed in real time.
We want to check the Laser’s Y position to see if it has moved off of the screen and that was determined to be 8 or greater. Once the Y position has hit that mark, Unity has a simple command of Destroy, where you will need to pass in what Game Object you want to destroy. In this case, we want to destroy the Game Object that the script is attached to so we pass in (this.gameObject). There you go. The cycle of life. What we once created, we now have destroyed.