How to Destroy Game Objects in Unity 3D
As important instantiating and modifying gameObjects is in a game, it's equally important to destroy them when they are not required.
Main reasons for destroying gameObjects include managing memory, getting rid of not-needed gameObjects (Like those that go beyond the camera and don't return), or even game-related events (Getting hit by a bullet).
Destroy(gameObject):
That's the code which is used to destroy a gameObject. Fairly simple, isn't it? Let's rewind and have a slightly more deeper look at what's going on. If you try to explore the Destroy
method in your IDE, you will see that the Destroy method has 2 variants(overloaded forms).
The first overload form simply Destroys the gameObject that's input as a parameter, and nothing else.
While, the second overload form, involves another parameter time, t
as a float
variable. This will wait for the time specified in seconds before destroying the gameObject. This variant of the Destroy
method comes very handy when you want the gameObject to finish up some other stuff/task/calculation before destroying itself. For example, playing a dying animation or adding a score.
Till our last tutorial, we've successfully added a target that outputs a message to the console when hit by a bullet. Now let's make the target vanish, once its hit, shall we? How do we do that? We simply add the following lines to our already existing target's script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetBehaviour : MonoBehaviour
{
void onCollisionEnter2D(Collision2D col)
{
// When target is hit
if(col.gameObject.tag == "Bullet")
{
Debug.Log("Target was Hit!");
}
// object which collided
Destroy(col.gameObject());
// object with which it collided
Destroy(gameObject);
}
}
What's going on here? We're telling the script to destroy the gameObject included in col's data. In simpler terms, it means we're telling the script to destroy the bullet(fireball), since we don't want our bullet to keep going after it destroys our target.
In the second Destroy
statement (our magic line), the gameObject destroys itself. Remember that simply using the term gameObject
references that gameObject which the script is attached to, in our case, the target. Save up the script, and fire up the game!
INFO: In editing mode.
INFO: In Play mode, after the target is hit
Once we hit the target, the bullet and the target disappear! Have a look at the Hierarchy, and you'll notice that the target and bullet's clone gameObjects both are missing. They have simply vanished out of existence once they get destroyed in-game. Since we placed the target in the scene while building it, it will always come back whenever we re-enter the scene, that is, whenever we enter Play mode.
So there you have it! Destroying gameObjects in itself is a very easy concept, since it involves only one line of code, but the real magic happens when you call the method along with other statements to make the object's destruction look and feel real and right.
We have done quite a lot this time. We gave our character the ability to shoot bullets, and we've learned the concepts of prefabs and instantiation. Next, we gave our character a target to shoot, thus understanding collision detection, and finally, we made the targets destroy themselves once they got hit, finishing things off with object destruction.
Practice Exercise
-
Try to give your target a Health value, meaning you have to shoot it multiple times to break it. This will test not only your logic in making games, but your ability to reason in basic programming logic as well.
HINT: A simple integer
variable and an if
statement can go a long way.
- Try to create an end-region for bullets out of the camera coverage area. If a bullet goes out of the camera region and touches this end region, it gets destroyed, instead of aimlessly going off into dead space. This is an efficient way of managing memory when you get into bigger, more complex games.