- Home /
Problem with health deduction
I've got a problem. I have two scripts, an enemy script and a bullet script. On the bullet script is this function to deduct health from the enemy inside an OnCollisionEnter
:
if (collider.gameObject.CompareTag ("Enemy")) {
collider.BroadcastMessage("ApplyDamage", 25.0);
}
I have this script on the enemy to take damage:
function ApplyDamage(damage : float) {
hitPoints -= damage;
if (hitPoints <= 0.0) {
Destroy (gameObject);
}
}
Now, this won't work. Any ideas? Thanks a lot.
EDIT - some additional info:
The enemy is a simple box at the moment with a character controller. It has a gun as a child, without any collider. I have an AI script and a damage reciever script attached to it. When I send it a message to do ApplyDamage
from my bullet, nothing happens. The function isn't called. I'm frustrated.
EDIT - some more additional info:
My script works the first time, but then every additional time, it doen't. Almost like it's destroying itself after the first hit. Any more ideas? I've spent a day and a half on this. And yes, I am logging a collision, because my bullet explodes on contact. And, he follows me the first time until I shoot him. Then, he stops moving as well.
Answer by dhendrix · Apr 26, 2010 at 06:24 PM
Your code is fine as far as I see, so you'll have to do some debugging. Is the enemy receiving the SendMessage at all? If not, then is the collision even happening? How is your enemy structured? As in what is the hierarchy of gameObjects, and which has the collider, rigidbody, and script?
EDIT: Is the console logging an error message along the lines of "SendMessage Function has no receiver!" ? I think the issue is that you aren't logging a collision to begin with. I'm not sure that CharacterControllers send OnCollisionHit messages, but instead OnControllerColliderHit.
I'm not 100% sure your characterController would log a collision in your example. Try using a Debug.Log statement to check if you are getting a collision.
Your answer
![](https://koobas.hobune.stream/wayback/20220612192321im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Setting Scroll View Width GUILayout 1 Answer
Expressions in statements must only be executed for their side-effects? 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
What is wrong with my HealthBar/Damage Script? 2 Answers
How can I make my enemy attack me every few seconds? 3 Answers