Enemy Detect Player's Raycast

Hello!

Basically I am making a zombie fps, and have made it so i have a working gun, which is using raycast.

What I want, is some help making my zombies detect the player’s gun’s raycast. Then obviously take health off the zombie.

Can someone help me go about doing this?

Thanks!

Put this in your update:

void Update()
{
   if( isFiring )
   {
      RaycastHit hit;
      if (Physics.Raycast(gunTipObject.transform.position, gunTipObject.transform.forward, out hit, 1000.0F))
      float distanceToGround = hit.distance;
      if( hit.collider.tag == "Enemy")
      {
        hit.collider.gameobject.SendMessage("ApplyDamage", weaponDamage);
      }
   }
}

If the enemy object’s script has a function called ApplyDamage( int damageInput ) , then you can subtract from the health of the enemy depending on its type, armor etc. You can replace SendMessage with a more efficient event handling system using events and delagates

Please bear in mind that this is only partial and untested code.

In the gun script that makes the raycast you can get the object which it hit and test if that is the zombie and then deduct health of the zombie, by accessing the component on the zombie that contains the health variable.

So basically it becomes the gun that access the health variable on the zombie script.

The outbound reference parameter is documented in the bottom of this page.