Error in scripting (HeadShot code)


if(Hit.collider.tag == "Head")
        var obj2 : Transform = Instantiate(BodyImpact,Hit.point,Quaternion.FromToRotation(Vector3.forward,Hit.normal)) as Transform;
        obj2.transform.parent = Hit.collider.transform;
        Hit.transform.GetComponent(HEALTH).HealthOfEnemy -= Damage * 100;


    if(Hit.collider.tag == "NPC")
    	var obj : Transform = Instantiate(BodyImpact,Hit.point,Quaternion.FromToRotation(Vector3.forward,Hit.normal)) as Transform;
        obj.transform.parent = Hit.collider.transform;
        Hit.transform.GetComponent(HEALTH).HealthOfEnemy -= Damage;

Ok so here is the problem. Both codes work! The problem is that the HeadShot code works but only if I tag the parent as “Head”, if I tag the head as “Head” nothing happens… If I tag the head as “NPC” again nothing happens, but if I tag the parent of the head as “NPC” the normal damage is applied… What gives?

Excerpt from the above link:

“The gameObject, collider, and rigidbody in the Collision parameter all refer to the topmost object involved in the collision. To determine which sub-collider was hit, you need to look at the contact points’s thisCollider or otherCollider depending on whether you’re calling OnCollisionEnter on the target or the projectile.”

To clarify if there is any confusion, when you have a compound collider setup, which means you have child objects that have child colliders, they will all report to the Parent of all the Children in terms of collisions. Since this is the case, you need to have individual scripts on each object to determine what object was hit, and then report that back to the parent.

BTW, if HEALTH is a class that you made yourself, I would suggest you rename it to Health. In the context of C programming, something with all capital letters typically refers to a constant variable that never changes. Not that big of a deal if you’re working by yourself, but if you ever plan to work with others, it’s probably a good idea to get rid of that habit right now.