I have been having a huge amount of trouble figuring out how to call an ApplyDamage function when a “Bullet” prefab rigid body collides with an other object. Each of these objects collided with have a C# script attatched called CharHealth which is this:
using UnityEngine;
using System.Collections;
public class CharHealth : MonoBehaviour {
public float maxHealth = 100f;
public float health = 100f;
public float minHealth = 0;
void Start(){
health = maxHealth;
}
public void ApplyDamage(float damageTotal)
{
health -= damageTotal;
Debug.Log ("Damage " + damageTotal + " was applied");
if (health <= 0)
{
health = minHealth;
Death();
}
}
void Death()
{
Destroy (gameObject);
}
}
I know this script works because I have a melee range enemy that already calls it sucessfully based around how close they are to the player. The problem I have been having is where do I assign a collider script to? The rigid body bullet? or the characters being fired upon.
This is the script I have applied to the bullet for now which isn’t working:
public class CollidingScript : MonoBehaviour {
void OnColliding(Collider col){ // col is a reference to the collider hit
if (col.gameObject.name == "TargetCube"){ // if the collider belongs to the Player...
//col.SendMessage("ApplyDamage", 5); // send the message to its owner
Debug.Log ("Collision Detected");
Destroy (col.gameObject);
}
}
}
I was using this API as reference https://unity3d.com/learn/tutorials/modules/beginner/physics/on-collision-enter and having very little luck. It was erroring with the message “On Colliding has to be of type collider” or somethign along those lines. Follow up question: does this OnColliding() function need to be called in an update, or is it automatic?