- Home /
Enemy health. Need to take damage from two different bullet prefabs
Hi guys
I need for an enemy to take damage from two different bullet prefabs.
bullet and bullet1.
var health : int = 100;
var prefab : Transform;
var sound : AudioClip;
var Points : Transform;
function OnCollisionEnter (hit : Collision) {
if(hit.gameObject.CompareTag("bullet") {
health -= 25;
AudioSource.PlayClipAtPoint(sound,transform.position);
}
if(hit.gameObject.CompareTag("bullet1")) {
health -= 15;
AudioSource.PlayClipAtPoint(sound,transform.position);
}
if (health <= 0) {
Destroy(gameObject);
AudioSource.PlayClipAtPoint(sound,transform.position);
var instanceBullet=Instantiate(prefab, transform.position, Quaternion.identity);
var instanceBullet1=Instantiate(Points, transform.position, Quaternion.identity);
}
}
The problem is my enemy only gets destroyed with the first prefab bullet. And the second prefab bullet1 doesn't destroy the enemy.
Any help would be appreciated.
Answer by TowerOfBricks · Jul 28, 2012 at 01:22 PM
Hm... I edited your post to fix code formatting. Perhaps I fixed the bug by mistake. Because now I cannot find anything wrong with your code. What would have caused it would be if you had written
if (health == 0) {
Since 25*4 is 100, and the health would therefore reach exactly 0, but 15*7 is 105, which would mean that the health would go to -5 directly. So an exactly == 0 check would fail. I was too quick fixing the formatting so I don't know if there was a < symbol there (some of the code was converted to html entities).
Otherwise you just have to check if the other bullet really has a "bullet1" tag. Make sure the object with the collider has it, not some other GameObject which might be connected to the bullet.
It seems the formatting was to blame. It is working now.
if(hit.gameObject.CompareTag("bullet") { health -= 25;
AudioSource.PlayClipAtPoint(sound,transform.position);
}
if(hit.gameObject.CompareTag("bullet1")) {
health -= 15;
AudioSource.PlayClipAtPoint(sound,transform.position);
}
I hadn't written the {} in the if conditions.
Thank you so much.
i tryed this script, it works to an extent, but i tried editing it to work with 4 bullets and broke ti. how do you do it?
Your answer
Follow this Question
Related Questions
enemy ai going to player 2 Answers
Shooting and health Help 0 Answers
Enemy Health Help 1 Answer
How can I lose health when my enemy collides with the player? 1 Answer
How to have an NPC with multiple parts detect damage 1 Answer