Ok, I am creating a 3d shooter game and I have a player that can shoot 'bullets' at the enemies. I can simply use OnTriggerEnter on the bullet to detect whether it collided with an enemy and then destroy the enemy. But what I would like to do is set up the enemies to withstand 3 hits or something and then destroy the enemy.
I have tried adding a health variable and every collision subtract 1 from the variable until it reaches zero, but when I play the game the lives don't subtract and the enemy is never destroyed. So I set the Health variable to a static variable but then if I have 2 enemy prefabs on the scene it takes 3 hits between the 2 enemies to destroy them. Is there any way to limit the health to the enemy that was hit? below is my script.
//Define Variables
var explosion : GameObject;
var scoreadded : boolean = false;
var health = 3;
var obj : GameObject;
function OnTriggerEnter (theObject : Collider)
{
if(theObject.gameObject.tag=="enemy")
{
//Instantiate(explosion, theObject.gameObject.transform.position, theObject.gameObject.transform.rotation);
//Destroy(theObject.gameObject);
health -= 1;
obj = theObject.gameObject;
}
}
function Update() {
if (health <= 0)
{
Instantiate(explosion, obj.transform.position, obj.transform.rotation);
Destroy(obj);
}
}
What you could do is call a function on your Enemy object rather, and have it track it's own health and when it should die, etc. You can also that way avoid checking every update if it should be killed and just do the check in the Damage function.
So in your Enemy object script. Not your bullet. I am just assuming the scrip name is "EnemyBehaviour", you can replace all occurences of "EnemyBehaviour" with whatever name your Enemy script actually has.
var health : int = 3;
function TakeDamage(Damage : int)
{
health -= Damage;
if (health <= 0)
{
Destroy(gameObject);
}
}
Then in your Bullet object script.
var damage : int = 1;
function OnTriggerEnter (theObject : Collider)
{
if(theObject.gameObject.tag=="enemy")
{
theObject.gameObject.GetComponent(EnemyBehaviour).TakeDamage(damage);
}
}
Give that a go and see how it works. I'm at work at the moment, so haven't tested it.
Also, let me just explain the result you were seeing with making the "health" variable static in your explanation.
Making a variable static, means that all instances of that object that are created share that ONE variable, the variable is only created once, when the first instance of the object is created, after that any other object instances created just reference the already created variable.
That is why when you minus one in one object, and minus one in another, those objects see their health as having gone down by 2, and not 1 as you expect.