- Home /
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
Answer by asafsitner · Dec 23, 2011 at 11:35 AM
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);
}
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
Oh, of course, if the field is public. I presumed it was private for some reason. :P
Your answer
Follow this Question
Related Questions
Raycast shooting in the middle of the screen 1 Answer
FPS shooting 1 Answer
Need coding help with fps 0 Answers
FPS aim marker Question 0 Answers
How do i make a Railgun style effect with a raycast shot? 1 Answer