Can someone explain the destroy () command?

I am working on a health system that involves the player taking damage when a creature hits him. I began researching the different script references that I would be able to use, and I came across Object.Destroy () (Unity - Scripting API: Object.Destroy)
I was confused on how to use that command, to simply delete a game object after a certain number of hits, but the Object.destroy command is not working!

Can someone please explain how to use this reference, and give me a few examples on how to use it to delete game objects?

JavaScript only, please

I haven’t started the script yet…
…but the Object.destroy command is not working!

:slight_smile:

Anyhow, if you want to destroy a game object then your first task is to get a reference to the object. If you know that your game object is called “Enemy” and you have no reference to the game object yet, you can use GameObject.Find(“Enemy”) to obtain it.

var enemyGameObject = GameObject.Find("Enemy");

Then to destroy it, just call Destroy(enemyGameObject).

So your code should probably look something like this when you want to destroy that game object:

var enemyGameObject = GameObject.Find("Enemy");
Destroy(enemyGameObject);

Note that looking game objects up by name can be a problem. Consider what should/would happen if you had 3 enemies, all called “Enemy” for example.

A better solution might be to grab the game object from the object you are colliding with (or however you detect hits) using Destroy(colliderOrScriptOfEnemy.gameObject);