Destroying Game Objects in Unity Using a Simple Cube and Box Collider
Objective: To show you how to destroy your game objects through code in Unity using a simple cube with a box collider.
Destroying the Laser Game Object Using a Box Collider
Let’s use a separate game objects box collider to Destroy the lasers as they both collide with each other.
Add a new 3D cube to the project and move it so it is out of sight above the play screen window and stretch it out so it covers the length of the window as shown below:
Let’s also create a tag for this object and call it ‘OutOfBounds’ which we will later look for in our code that we create.
Now let’s add a box collider to this by using ‘add component’ when you have the cube highlighted. You will now see green lines around the edges of the box and these indicate the size of the box collider. If you need to adjust the size of this to fit the rectangle, simply click on the box symbol as shown below:
and your cube should now have small squares that you are able to drag around and adjust your scale:
We also need to a add a new component — ‘Rigidbody’ to our game object in order to register the collision. As we aren’t using gravity in our game, let’s remove this option and tick ‘Kinematic’ instead. Kinematic controls whether physics affects the Rigidbody and by ticking this option, physics will not.
Now that we have both of these 2 components on our OutOfBounds game object, let’s make sure we have also ticked the ‘Is Trigger’ option in the Inspector as we are going to be using a piece of code that is looking for this and this is a crucial step that many people miss.
Let’s add the piece of code we are missing to our Laser script:
Let’s break this down:
private void OnTriggerEnter(Collider other)
// Create a new built in method called OnTriggerEnter(Collider collision). As you can see I have changed the collision variable to ‘other’ and you can name this whatever you want as you are simply creating a new variable.
if(other.tag == “OutOfBounds”)
// We are saying, if the ‘other’.tag is equal to “OutOfBounds”, then we are going to do something:
Debug.Log(“Laser hit the collider”);
// This will tell us in the console window if our laser has interacted with the OutOfBounds game object for debugging purposes.
// Then, destroy this game object.