- Home /
How to destroy GameObject's script(s)?
So I am trying to make so that when I am shooting the enemies, they could stop moving (Deleting the EnemyAI script by killing him) and I tried to do the: Destroy.script(EnemyAI) or Destroy(EnemyAI.js) but nothing is working. Please help!
It depends on where this Destroy() is co$$anonymous$$g from, and getting the syntax right. Post how you are defining EnemyAI
Try this
http://docs.unity3d.com/Documentation/ScriptReference/Object.Destroy.html
Answer by jjkiii · Aug 09, 2014 at 03:20 AM
Mattsson almost completed the question. In C# i would...
OnTriggerEnter(Collider other)
{
//assuming your bullet is tagged as bullet and the enemy has no health.
if(other.gameObject.tag == "bullet")
{
Destroy(GetComponent<EnemyAI>());
}
}
Put this on the same object that the EnemyAI script is!
You can use GetComponent() for many things as shown here: http://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
Hope This Helps! =D
Answer by rutter · Aug 09, 2014 at 03:12 AM
If you're making the destroy call from the EnemyAI:
Destroy(this);
If you're doing it from some other object:
//C# version
//assumes you have a GameObject variable named "enemy" which is NOT null
Destroy(enemy.GetComponent<EnemyAI>());
//JS version
Destroy(enemy.GetComponent(EnemyAI));
It's impossible to give more detail without knowing more about your scripts. If you can tell us more about your setup, we might be able to give a more specific answer.
In general, though, you should probably look up GetComponent tutorials.
Answer by mattssonon · Aug 22, 2013 at 07:13 AM
You need to get ahold of the component properly, e.g. by running Destroy(GetComponent(EnemyAI));
. But I would suggest you create a static variable, e.g. a bool
called canMove
, in EnemyAI.js
, which controls whether or not the enemy is moving, and then set this variable to false instead of running Destroy()
.
Bad idea, a static variable will restrict you to only one enemy.