- Home /
How to have an NPC with multiple parts detect damage
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.
Answer by Ed unity · Apr 18, 2014 at 02:34 PM
In your case, you only want to have the enemy script attached to the Root Game object that every other piece of the enemy is under. So you said that you made all other objects a child of an empty game object. You should only need to attach the script to the empty GameObject and then that object will be the one you need to access in order to call the functions and apply damage.
Your answer
Follow this Question
Related Questions
The enemy don´t lose health, but why??? 0 Answers
Prefab shooting damage/health? 1 Answer
Melee Damage script by collision 2 Answers
how do i damage the player on enemy start, Not collision 2 Answers