- Home /
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 () (http://docs.unity3d.com/Documentation/ScriptReference/Object.Destroy.html) 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
In regard to but the Object.destroy command is not working : Can you show us your current script please, thanks.
http://video.unity3d.com/video/7720450/tutorials-using-unity-answers
I haven't started the script yet, I came here to do some clarifying first. If I said like OnCollisionEnter, and the other object's name is enemy, how would I use Destroy () to delete this object, like can you tell me how I would use this to delete a gameobject.
I am planning to apply this to a projectile, so that when the projectile hits an object (such as an enemy) with the specified Gameobject name, the enemy will dissapear. I'm not looking for a health system, just a "one hit kill" system. If you really are confused on what I want, I will attempt to write a script. I have very little Javascript knowledge, So be prepared.
Can you just post a simple example, like "if (trigger) happens, delete (this) object.
thanks in advance
Answer by Statement · Mar 10, 2013 at 03:39 AM
I haven't started the script yet... ...but the Object.destroy command is not working!
:)
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);