OnTriggerEnter called only one time?!!

Im trying to do a simple shooting AI but the ai doesn’t stop shooting when the Player leaves the collider, he just keeps shooting for ever, anyone could fix it please?

var Bullet : Rigidbody;
var Spawn : Transform;
var BulletSpeed : float = 1000;
var shootsound : AudioClip;
var attack : int = 0;
var FireRate = 1;
var canfire = true;

function OnTriggerEnter(pInSight : Collider){
    if(pInSight.gameObject.tag == "Player"){
        attack = 1;
    }

    if(!pInSight.gameObject.tag == "Player"){
        attack = 0;
    }
}


function Update () {
    if(attack == 1)
    {
        Shoot();
    }
}

function Shoot () {
    if(canfire == true){
        var bullet2 : Rigidbody = Instantiate(Bullet,Spawn.position,Spawn.rotation);
        bullet2.AddForce(transform.forward *BulletSpeed);
        GetComponent.<AudioSource>().PlayOneShot(shootsound);
        canfire = false;
        yield WaitForSeconds(FireRate);
        canfire = true;
    }
}

OnTriggerEnter is only called when something enters the trigger. Use OnTriggerExit instead and always try searching before posting!

The OnTriggerEnter is called when the player enters the Trigger. To register when something leaves the Trigger area, use OnTriggerExit instead.

Also, if Shoot is a coroutine, you can’t simply call it, you need to call it using StartCoroutine():

you could use the OnTriggerExit () function like this:

 var Bullet : Rigidbody;
 var Spawn : Transform;
 var BulletSpeed : float = 1000;
 var shootsound : AudioClip;
 var attack : int = 0;
 var FireRate = 1;
 var canfire = true;
 
 function OnTriggerEnter(pInSight : Collider){
         if(pInSight.gameObject.tag == "Player"){
         attack = 1;
     }

 function OnTriggerExit(pInSight : Collider){
         attack = 0;
     }
 }
 
 
     function Update () {
     if(attack == 1)
     {
         Shoot();
     }
}
 
 function Shoot () {
     if(canfire == true){
         var bullet2 : Rigidbody = Instantiate(Bullet,Spawn.position,Spawn.rotation);
         bullet2.AddForce(transform.forward *BulletSpeed);
         GetComponent.<AudioSource>().PlayOneShot(shootsound);
         canfire = false;
         yield WaitForSeconds(FireRate);
         canfire = true;
         }
 }

If you want the player to be shot only while in the collider use:
OnTriggerStay()

If you want the player to be shot only when entering the collider:
OnTriggerEnter()
However this will only happen once (specifically when the collider is entered, hence the name)

If you want the player to be shot only when exiting the collider:
OnTriggerExit()
However this will only happen once (specifically when the collider is exited, hence the name)

Its very simple.

 if(attack == 1)
 {
     Shoot();
     attack = 0;
 }