- Home /
raycasting gun hitting random spawned enemies when shooting at one of them?
Hey guys and gals, I'm having an issue in unity with my raycasting gun. You see, I'm using a spawner that spawns zombies, which are, of course, clones of a prefab. The problem is, when I try to reduce the health of one of the enemies using GameObject.FindWithTag("Enemy").GetComponent().currentHealth -= damage; using my raycasting gun , the damage is recognized but is applied to a random clone since they all have the same object name and the same tag. Is there a way around this? Thanks!
Answer by OryxW · Dec 10, 2021 at 02:22 AM
further details : I pretty much need it to do the damage to the zombie im aiming at and shooting, but since they're all clones, unity doesn't seem to make the difference, so it just depletes the health of random clone somewhere on the map.
Answer by Eno-Khaon · Dec 10, 2021 at 03:15 AM
For reference, part of your post was eaten by HTML-style markup (namely, use of < and > around text not in a code block). Do note that if your post preview doesn't look right, neither will the resulting question.
Well, you're using a Raycast to determine whether you're hitting a zombie. You don't need to Find() an arbitrary one after that.
RaycastHit hit;
if(Physics.Raycast(ray, out hit)) // whatever parameters you're using
{
ZombieScript zs = hit.collider.GetComponent<ZombieScript>();
// Replacing variable reduction with a function call
// for a better place to check whether the zombie has
// run out of health
if(zs != null)
{
//zs.currentHealth -= damage;
zs.TakeDamage(damage);
}
}
Edit: Added a safety check for good measure
ohhh, I can actually do that? I thought I had to search for the script of the zombie, since the raycast function is on the gun and the health is on the zombie.
Your answer
Follow this Question
Related Questions
Can't find a clone object with RayCast? [Solved] 2 Answers
Raycast script help? 1 Answer
Help finding out which side of a cube a raycast hits 1 Answer
RaycastHit always returns 0 1 Answer
RaycastHit.point Collider issue C# 0 Answers