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;
}
}
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)