In the last article, we discussed instantiating Game Objects in code by adding laser shots — but what happens after the laser moves off screen?
Once fired, the lasers go up and up forever. So, to balance the power of instantiation — let’s take a look at destroying GameObjects.
Destroy the Object
While the Laser object had to be created from the Player script, you can destroy it from the Laser script. First, let’s establish the conditions under which the laser should be destroyed.
In Update(), you can check to see if the laser has passed the upper boundary of the screen to determine if it should be destroyed. Using the SerializeField attribute, you can set the value of _yMaxBoundary from the Inspector.
To actually the destroy the object, you can use the Destroy() method and pass in a reference to the object to destroy. Since you are calling this from within the Laser script, you can use the this keyword to refer to the script itself. As you can see above, the laser object remains but stops moving once it moves off-screen. This is because the Laser script is destroyed, but not the Game Object attached to it — so Transform.Translate is no longer being called every frame.
To get a reference to the Game Object attached to this script, pass in this.gameObject.
Now, the Laser object is destroyed entirely.
Be sure to destroy Game Objects you no longer need to keep your game running smoothly. And remember: “With great power comes great responsibility.”