- Home /
Changing variable in a script of a game object hit with raycast
I have a script that is my gun shooting script (with raycast), and another one that has my enemies health. I want to know how to make it so that when my enemy gets hit with raycast, the variable zHealth goes down for only the zombie hit with raycast. The enemies are all instantiated clones of the same game object.
shootingGunScript
#pragma strict
var zHealth = 3;
var spawnPoint : Transform;
var muzzleFlash : Renderer;
var MuzzleLight : Light;
var Zombiebehaviourscript : Zombiebehaviourscript;
//var shotSound : AudioClip;
function Start () {
muzzleFlash.enabled = false;
MuzzleLight.enabled = false;
}
function Update () {
if(Input.GetMouseButtonDown(0)){
var hit : RaycastHit;
var rayray = Physics.Raycast(spawnPoint.position, spawnPoint.forward, Mathf.Infinity);
Debug.DrawRay (spawnPoint.position, spawnPoint.forward*10, Color.green);
Shoot();
if (Physics.Raycast(spawnPoint.position, spawnPoint.forward, hit, Mathf.Infinity)){
Zombiebehaviourscript.zHealth -= 1;
}
}
}
function Shoot (){
muzzleFlash.renderer.enabled = true;
MuzzleLight.enabled = true;
yield WaitForSeconds (0.02);
muzzleFlash.renderer.enabled = false;
MuzzleLight.enabled = false;
}
Zombiebehaviourscript
#pragma strict
var zHealth = 3;
var zspeed = 5;
var attackTimer = 1;
var attackRange = 1.5;
var zdead = false;
var target : Transform;
var zTransform : Transform;
var healthPlayer : healthPlayer;
var zombie = GameObject;
function Start () {
}
function DestroyThisGameObject()
{
Destroy(this.gameObject);
}
function Update () {
if(zHealth < 1){
zdead = true;
}
if(zdead == true){
DestroyThisGameObject();
}
transform.Translate(Vector3.forward*zspeed*Time.deltaTime);
transform.LookAt(target);
//
////
var distance = (target.position - zTransform.position).sqrMagnitude;
if(distance < attackRange && Time.time > attackTimer){
healthPlayer.totalHealth -= healthPlayer.damage;
attackTimer = Time.time + 2;
Debug.Log ("Hit");
}
////
//
}
function FixedUpdate(){
}
Answer by Berenger · Jun 30, 2012 at 08:47 PM
You need the reference of the zombi script attached to the gameobject hit by the ray. You can have it with the raycasthit (you have access to collider and transform, and from there everything). Use GetComponent, and decrease the health.
While I'm at it, you're using 2 identical raycast for no reasons. You only need one. And you need a timer so the player cannot fire continuously.
Your answer
Follow this Question
Related Questions
Instantiate JS error that i can't figure out 1 Answer
How to activate a button? 1 Answer
How do I assign a var to the object I've just instantiated? 2 Answers
Gun Script Help 2 Answers