Accessing Functions in other gameObjects

Hi Guys, this is driving me CRAZY! I’ve been at this for over a week now and can’t find an answer.

I’ve got a player, and a bunch of zombies.

The zombies are dropped in via prefab.

The player has a weapon, when fired, it shoots a ray.

Zombies spawn and self create themselves.

Ok, my problem is, the zombies have a ‘applyDamage()’ function on themselves as well as a life variable (private var life = 50). How do I trigger that function to damage that zombie only (one that was hit by ray). So far I’ve only managed to damage all zombies.

After raycasting, you simply check if hit was a “zombie” (in the example, I did this by checking tag) If it was a zombie, you then call GetComponent to access the zombie script, then call their ApplyDamage method. (replace “Zombie” betwen < and > with your zombie script’s name, whatever it is)

Here is a c# example (I don’t use UnityScript so I can’t post a UnityScript example):

Ray ray = Camera.main.ScreenPointToRay(crosshairPosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit) && hit.collider.tag == "Zombie")
{				
	hit.collider.GetComponent<Zombie>().ApplyDamage(playerDamage);
}

An alternative is replacing the GetComponent call with:

hit.collider.SendMessage("ApplyDamage", playerDamage);

Remember that if you are using c#, you need to make ApplyDamage method “public” or you won’t be able to access it from another script.

Please don’t forget to click the checkmark near the answer if it solves your problem or post comments if something confused you.