- Home /
Having trouble with raycast detecting enemy
I have a script casting a raycast from the center of the screen at to a certain distance looking for the colliders of any enemy tagged as "enemy". But according to my debug log, it only seems to detect one specific enemy and ignores the others. From what I can see, there's nothing different about this enemy than the others (they're all from the same prefab). Here's the script:
public bool inPlayerSight;
public float playerSightDistance;
private Animator anim;
private DoneHashIDs hash;
private Transform cam;
private bool spotted;
private GameObject enemy;
void Awake(){
anim = GetComponent<Animator>();
hash = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent<HashIDs>();
enemy = GameObject.FindGameObjectWithTag(Tags.enemy);
}
void Start() {
spotted = false;
}
void Update(){
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if(Physics.Raycast(ray, out hit, playerSightDistance)){
if(hit.collider.gameObject == enemy){
spotted = true;
Debug.Log("Enemy spotted");
}
else
{
spotted = false;
}
}
}
Each enemy has a capsule collider for their physics collider and a sphere collider set to Is Trigger which represents their area of vision. They're all tagged Enemy. What could possibly make it so only one specific enemy is detected by the raycast?
Are all of the enemies clones of the prefab? I had this exact problem not long ago. What happened to me was when any of the enemies were detected by the raycast only the original enemy was affected.
I think that may be the issue here. What did you do to resolve it?
Answer by LT23Live · Aug 25, 2014 at 01:24 AM
im not sure but i think your problem might have been the way you used gameobject.findwithtag.
GameObject.FindGameObjectWithTag("enemy");
thats the way it is show on Scripting API http://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html
Ah, I see So is it possible that the raycast is only detecting one enemy because FindGameObjectWithTag is only finding one enemy ins$$anonymous$$d of all of them?
Your answer
![](https://koobas.hobune.stream/wayback/20220613161446im_/https://answers.unity.com/themes/thub/images/avi.jpg)