Prefab shooting damage/health?

I can’t seem to get my damage and health system working. If someone could take a look and tell me what I’m doing wrong, it would be greatly appreciated.

This is my Health.cs script that I attach to things I want to be able to kill.

using UnityEngine;

public class Health : MonoBehaviour {

    public int maxHealth = 100;
    public int currentHealth;
    public bool alive = true;

    public void Start()
    {
        currentHealth = maxHealth;
    }
    public void TakeDamage(int damageAmount)
    {
        if(currentHealth < 1)
        {
            alive = false;
            Destroy(this.gameObject);
        } else
        {
            alive = true;
            currentHealth -= damageAmount;
        }
    }
}  

This is my damage script that I currently have attached to the projectile that will be colliding with the enemies.

using UnityEngine;

public class Damage : MonoBehaviour {

    public int damageAmount = 10;

    public void OnCollisionEnter(Collision col)
    {
        if(col.rigidbody)
        {
            col.rigidbody.GetComponent<Health>().TakeDamage(damageAmount);
        }
    }
}

Thanks in advance to anyone that lends me a hand.

to elaborate on my code and what I’ve tried, this is what my Damage.cs script was originally, but the one I posted above is what I changed it to while trying to get this to work.

using UnityEngine;

public class Damage : MonoBehaviour
{

    public int damageAmount = 10;

    public void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.tag == "Collide")
        {
            Health _health = col.gameObject.GetComponent<Health>();
            _health.TakeDamage(damageAmount);
        }
    }
}

The object I am trying to take health away from is tagged with the “Collide” tag. I’m not understanding why this isn’t working. Someone that knows something about Unity, please help me.
@thetomfinch

Hey.
Let’s say you have Enemy and Player game objects on scene.


  1. Make sure you attached Health to Player game object.

  2. Make sure you have Collider and Rigidbody on Player.

  3. Make sure your Player has a tag Player.

  4. Make Sure you have attached Damage script to Enemy game object.

  5. Make sure you have Collider (uncheck “is trigger”, we don’t need trigger for now) and Rigidbody (uncheck “is kinematic”,because you can’t trigger oncollisionenter if you are kinematic) on Enemy.

And try this code:


    public void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.CompareTag("Player")) // it is similar gameObject.tag == "Player" 
        {
            Debug.Log("I have collision with Player! Trying to give him some damage!");
            Health _health = col.gameObject.GetComponent<Health>();
            if (_health != null)
                _health.TakeDamage(damageAmount);
        }
        else Debug.Log(col.gameObject.name);
    }