Destroying Game Objects in Unity Using the Transform.Position
--
Objective: To show you how to destroy your game objects in Unity using the game objects transform.position.
In the space game I am currently creating, I have added the feature of being able to shoot our lasers when we press the Space key. However, this is causing our Hierarchy to be flooded with instantiated Laser’s and it will eventually start to slow your game down.
Solution: Let’s get rid of them!
Destroying the Laser Game Object Using the Transform’s Position
Using the lasers current transform.position allows us to define a number at which we would like to destroy a game object on the y-axis:
Now as you can see I have hard coded in the number 12, this ISN’T best practice. What happens if you need to change this 20, 50 or 100 times in your code? You don’t have time to manually go through and find them all and change them. So let’s create a new variable to store this number and replace the hard coded 12:
Once our lasers transform.position is greater than 12 on the y axis, it will Destroy itself within the Hierarchy.
Next Up: Destroying Game Objects Using a Simple Cube and Box Collider
Useful Links:
https://docs.unity3d.com/ScriptReference/Transform-position.html