x


Using raycast gun to take down life of enemy when shot

Hey guys,

I currently have my gun setup in my FPS game so that the player can shoot, a muzzle flash occurs, and there is a blood particle system instantiated when the player shoots at the enemy. all I can't figure out now is how to take down the health variable of the enemy one by one each time the enemy is shot!!!!!

Here is my gun script!:

var hit : RaycastHit;
var bloodPrefab : GameObject;
var muzzlePoint : Transform;

function Update () {
    if(Input.GetButtonDown("Fire1")){
       StartCoroutine("Shoot");
    }

}

function Shoot(){
    var fwd = muzzlePoint.TransformDirection (Vector3.forward);
    if (Physics.Raycast (muzzlePoint.position, fwd, hit, 100)){
       if(hit.collider.gameObject.tag == "zombie"){
         Instantiate(bloodPrefab, hit.point, hit.transform.rotation);
       }
    }
}

That all works good!, but how would i take down the health of the enemy tagged "zombie" when it hits it. The zombie has a script on it called "zombie" and a health variable called "health" if that matters!

Thanks!

-Grady

more ▼

asked Dec 23 '11 at 01:08 AM

Grady gravatar image

Grady
1.1k 66 70 82

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

I suppose the easiest way would be to use SendMessage. Have a method in the Zombie's script that decreases it's health, and call it when the player hits.

if(hit.collider.gameObject.tag == "zombie")
{
    Instantiate(bloodPrefab, hit.point, hit.transform.rotation);
    hit.collider.gameObject.SendMessage("DecreaseHealth", amountOfHealthToDecrease);
}
more ▼

answered Dec 23 '11 at 11:35 AM

asafsitner gravatar image

asafsitner
2.4k 2 8 19

Hey,

Thanks for your response, I noticed I could do it with GetComponent pretty much the same way you showed here, but by going:

hit.collider.GetComponent(zombie).health --;

-Grady

Dec 23 '11 at 12:21 PM Grady

Oh, of course, if the field is public. I presumed it was private for some reason. :P

Dec 23 '11 at 01:04 PM asafsitner

Oh well, thank you for your help!!!!!!!!!!

Dec 23 '11 at 01:42 PM Grady
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1525
x1171
x445
x383
x274

asked: Dec 23 '11 at 01:08 AM

Seen: 936 times

Last Updated: Dec 23 '11 at 01:42 PM