Enemy ai Ignore walls! help!

Hello, it turns out that I have created an AI script that works like this: the enemy has a distance of detection of the player, when the player enters that area, the enemy looks at it until the player moves away, but it turns out that the enemy detects my player through the walls or colliders (I mean, if I hide behind a wall he detects me the same), does anyone know anything? Thank you!

#pragma strict

var Target : Transform;
var Animador : Animator;
var Distance : float = 30;
var rotationDamping : float = 2;

function Start ()
{
Animador.SetBool("Aiming", false);

}
 
 function Update()
 {
     var distance = Vector3.Distance(Target.position, transform.position);
 
     if(distance <= Distance)
     {
         LookAtTarget();
         Animador.SetBool("Aiming", true);
     }   
     if(distance > Distance)
     {
         Animador.SetBool("Aiming", false);
     }   

    }
 
 function LookAtTarget()
 {
     var dir = Target.position - transform.position;
     dir.y = 0;
     var rotation = Quaternion.LookRotation(dir);
     transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationDamping);
 }

Hi,

you could add a raycast before you actually turn towards the player. This can quickly become resource intense, especially if you have multiple enemies and call it in every Update() call.

You can use the following c# code snippet (untested)

void Update() {
    var distance = Vector3.Distance(Target.position, transform.position);

    if (distance <= Distance && IsPlayerVisible()) {
          ...
    }
    ...
}

boolean IsPlayerVisible(){
    Vector3 dir = Target.position - transform.position;
    //save the first hit into a variable.
    RaycastHit hit;
    if(Physics.Raycast(transform.position, direction, out hit)){
            //eg check the tag of "hit.transform" - is it the player or a wall?
            //if it is a wall, return false
    }
}

Remember, Multiple raycast per Update cycle are bad practice. You can add a counter, that gets increased every update and calls the raycast at value X.

Hope this helps, sorry, that I cant provide you with the javascript code