Destroying Enemy Help

I have already got a health script set up for an enemy I have but I don’t know how to make the enemy dissapear (die) when its health goes to 0, can anyone help?

5 Answers

5

I won’t be too specific on script, but I will show u basic idea. Here is if the script is attached to the enemy. If health is less than or equal to 0…

if(health<=0)
{
Destroy(gameObject);
}

And here is if script is attached to you, you need to assign the enemy in the inspector (drag and drop) by assigning a variable as Transform. You already know the health part, so I will just put how to destroy on 0. for “gameObject” make sure to use lower case g. The capital G “GameObject” is the component…

var enemy : Transform;
var enemy_health : float;

function Update()
{
if(enemy_health <= 0)
{
Destroy(enemy.gameObject);
}
}

Well, obviously the script will do nothing if health is above 0! if health is above zero, then the object should not get destroyed anyway!

–

To simplifiy, use enemy_health -= 10; it's less confusing.

–

You'll get more help if you provide more information. What does your script look like now? What line do you get the error on?

–

At the end of AddjustCurrentHealth() put in a check- if(curHealth <= 0) { GameObject.Destroy(gameObject); } Although, @jfhutchi, @kevork and @Clunk have already told you this! It's not that hard!

–

Could you please stop posting your entire script over and over! Just modify your original post, if you need to change something. What line does the error happen on? I can't just guess this stuff!

–

if (enemyHealth == 0) { Destroy(gameobject); }

if your enemy’s health is tracked on the Enemy GameObject than that should make it disappear. You could get “fancy” and instantiate a prefab of the enemy exploding(particles) and play a sound there too.

Never check ' == 0'. what if it gets set to -2? Your enemy will never die. Always use ' <= 0'

–

It’s probably where we have GetComponent(“Enemy_Health”); That means you need to change “Enemy_Health” to whatever your other script attached to the enemy is named. Since this is attached to the enemy, GetComponent will find any other scripts attached. If your C script you already have is named ehealth, e-health, enemyhealt, etc… Do GetComponent(“ScriptName”). Then whatever your health is called inside your script, you do a dot “healthname” so if your script is EnemyHealth, and the health variable inside it is called Health, you would do GetComponent(“EnemyHealth”).Health = 0. of course, you would use your own names and numbers.

How can I make this script work when I have a total of 4 enemies? please help!!

Assuming the health script is attached to the enemy gameobject, put this in Update() of the health script, and it will remove the enemy gameobject from the scene.

if(health <= 0)
     Destroy(gameObject);

Waste of Update(), use property getters or an OnHit() event function (as an example)

–