Accessing Script that Raycast hit

Hello, I’ve been at this for hours. I’ve got a level with a bunch of zombies placed from a prefab. They run around and try and kill the player.

The player has a weapon that casts a ray when mouse is down, and if it hits a zombie, it is meant to access that zombies health script and change its life value.

The problem I’m having, is when the ray hits any zombie, all zombies take damage. I’m not sure where I’m going wrong. This is my weapon script:

   #pragma strict
    
    private var fireRate : float;
    private var nextFire : float;
    var hit : RaycastHit;
    var weaponDamage : float;
    
    //Weapon sound effects
    var shotgunFire : AudioClip;
    
    function Start()
    {
    	//Set rate of fire
    	fireRate = 2;
    	weaponDamage = 1;
    }
    
    function Update()
    {
    	if (Input.GetButton ("Fire1") && Time.time > nextFire)
    	{
    		nextFire = Time.time + fireRate;
    		audio.PlayOneShot(shotgunFire);
    		
    		//Cast ray, if hit zombie, deal damage to selected zombie
    		if (Physics.Raycast (transform.position, transform.forward, hit, 100))
    		{
    			//This doesn't draw a line, I mustn't be using it correctly
    			Debug.DrawLine (transform.position, transform.forward);
    			
    			if (hit.collider.gameObject.tag == "zombie")
    			{
    				var enemyLifeScript = hit.collider.GetComponent(ZombieHealth);
    				if (enemyLifeScript)
    					enemyLifeScript.life -= weaponDamage;
    				
    				//Other Things I've tried:
    				//hit.collider.gameObject.GetComponent(ZombieHealth).life = hit.collider.gameObject.GetComponent(ZombieHealth).life - weaponDamage;
    				//ZombieHealth.life = ZombieHealth.life - weaponDamage;
    			}
    		}
    	}
    }
    
    @script RequireComponent(AudioSource)

Basically, how I would do this would be by placing a function inside of your zombie script that would inflict the damage, and the damage would be handled by a float parameter.

In your zombie health script, you can add something like this:

function ApplyDamage (damage : float) {
life -= damage;
}

And to do damage you would call the function on the hit object, and tell it how much damage to inflict:

if(hit.collider.tag == "zombie"){
hit.gameObject.SendMessageUpwards("ApplyDamage", weaponDamage); //Tell the game object you've hit to initiate a function called "ApplyDamage", and set the 'damage' float parameter to a desired value, which would be weaponDamage
}

Hope it works.

RaycastHit hit;
if(Physics.Raycast(CurrentWeapon.BarrelGO.position,CurrentWeapon.BarrelGO.TransformDirection(Vector3.forward),hit,250.0))
{
hit.transform.SendMessage(“ApplyDAmage”,CurrentWeapon.damage);
}

i use this …

replace currentweapon with the class that you are using for your weapons and barrelGO with the bullet spawnpoint (make sure the bullet-spawnpoint gameobject is pointing with the blue arrow torwards the direction of the shooting)