I have an enemy NPC built from several simple game objects (cubes, cylinders, etc.). I have followed a tutorial in making enemies take damage if they’re within a certain range, and the code works fine on single objects.
I have tried both placing all of the objects into an empty object and having them saved as a prefab, then applying the code to them, but when I play the game and attack the enemy, the health remains unchanged.
Code:
Attack code within Main character:
#pragma strict
var Damage:int = 25;
var Distance:float;
var enemyDistance:float = 2;
function Update()
{
if(Input.GetButtonDown("Fire1"))
{
var hit:RaycastHit;
if(Physics.Raycast (transform.position, transform.TransformDirection(Vector3.forward), hit))
{
Distance=hit.distance;
if(Distance<enemyDistance)
{
hit.transform.SendMessage ("ApplyDamage", Damage, SendMessageOptions.DontRequireReceiver);
}
}
}
}
Damage code within enemy:
#pragma strict
var enemyHealth:int = 100;
function Update ()
{
if (enemyHealth<1)
{
Dead();
}
}
function ApplyDamage (Damage:int)
{
enemyHealth -= Damage;
}
function Dead()
{
Destroy (gameObject);
}
Although I am relatively new to Unity, as far as I’m aware, this should work. Any help would be greatly appreciated.