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.
asked Apr 04 '11 at 08:14 AM
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.
Then in your Bullet object script.
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.
I hope that makes some sort of sense.
answered Apr 04 '11 at 08:48 AM