system
1
Hey,
So, I'm connecting a script, for applying damage, and the function is on its own script, and I want it to destroy whatever object it is on... (Being a prefab).
So, what I'm wondering is how do you make a line of code that makes the gameobject that the script is connected to to destroy...
Like,
if(health <= 0)
{
//What to put in place of the _'s?
Destroy(________________);
}
Any help would be great,
Thanks,
Justin W.
system
3
If you want to destroy the immediate gameObject.
It would be
if(health <= 0){
Destroy(gameObject);
}
But in the case of killing ennemies, you often want to kill the parent of the object and so it's.
if(health <= 0){
Destroy(transform.root.gameObject);
}
this check the attachments to the transform of the object and go up to the highest one.
PS:
The Unity Script reference is very usefull to get to know how the functions are built.
http://unity3d.com/support/documentation/ScriptReference/
system
6
This is much easier than you guys are making it. Just do this:
if(health <= 0)
{
Destroy(gameObject);
}
Or, if you have anything set to a variable you’d like to destroy, use this:
if(health <= 0)
{
Destroy(anObject.gameObject);
}
OR, if you are getting the error Cannot delete GameObject to prevent data loss, use this:
if(health <= 0)
{
DestroyImmediate(gameObject);
}
This is all it takes…
system
2
game.Object
but I've got to type more to post...
edit, my bad, don't know why I put the '.' there.
to reference the current script component’s calling object do:
var obj: GameObject;
obj= gameObject;
Bob5602
4
Actually, wouldn't it be gameObject? From the Unity reference :
// Kills the game object
Destroy (gameObject);
// Removes this script instance from the game object
Destroy (this);
// Removes the rigidbody from the game object
Destroy (rigidbody);
// Kills the game object in 5 seconds after loading the object
Destroy (gameObject, 5);
// When the user presses Ctrl, it will remove the script
// named FooScript from the game object
function Update () {
if (Input.GetButton ("Fire1") && GetComponent (FooScript))
Destroy (GetComponent (FooScript));
}