# C# Unity3D FPS apply damage to an enemy (Weapon bullet)

I am kindly new to Unity3d and c# and I don't understand how I could let a bullet deal damage to an other object. I've seen a lot of JS tutorials but no for C#. I've tried to use them, but it wont work. My code I've tried: For the Bullet (Prefab)

   using UnityEngine;
using System.Collections;

public class MoveBullet : MonoBehaviour {

public float speed = 10.0F;
public float damage = 10.0f;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

transform.Translate (0, 0, speed);

}

void OnCollisionEnter(Collision col){

}
}


And the one for the Enemy:

public class enemyhealth : MonoBehaviour {

public int health = 100;

// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}

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


What's not clear to me as well is, what type of Collider I should use (Box Collider, CapsuleCollider...) Or doesn't it makes a difference?

As I understood, Rigidbody is used for an other "technique" to make damage, am I right?

• pew pew, pew pew! – War Mar 23 '15 at 14:09
• Would it not make sense to just declare a Healthbar monobehaviour that tracks the health of a game object its attached to? then yes you are correct you need to handle a collision with say weapons / projectiles and basically do what you are already doing. – War Mar 23 '15 at 14:11
• isnt that almost the same what I am doing? – Jan Mar 23 '15 at 14:14
• Every bullet does have the upper script on it and the enemy has to 2nd script attached. But when the bullet hits the enemy, the health doesn´t become less... – Jan Mar 23 '15 at 14:16

Check Both objects (bullet and enemy) have a collider with 'Is Trigger' enabled plus the bullet has a rigidbody.

You can use the collider you prefer.

I rewarote youre code this way:

    // Update is called once per frame
void Update () {
transform.Translate (0, 0, speed);
}
void OnTriggerEnter(Collider Enemy){
if(Enemy.gameObject.CompareTag("enemy"))
{
Enemy.gameObject.SendMessage("OnDamage", damage);
}


My understanding from reading your code is that you send a message passing a param (the damage amount) ...

gameObject.SendMessage("OnDamage", damage);


You then declare a method that takes no params to handle it ...

void OnDamage(){


My guess is that the unity compilation process is not creating a correlation between these 2 because of that mismatch.