Hello. In my game, a enemy has a gun and when the player enters the trigger area, it is supposed to shoot every couple of seconds (if the player is still in the area of course). However, it is only firing once if the player doesn’t leave the area. I’ve worked out that this is because, for some reason, after the co-routine has gone through once, the variable (inArea) goes back to false but I don’t know why this is happening. Can anyone help?
Here is the part of my code responsible for the shooting:
void OnTriggerEnter2D ( Collider2D other ){
if (other.gameObject.tag == "Player")
inArea = true;
StartCoroutine(Shoot());
}
void OnTriggerExit2D ( Collider2D other )
{
if (other.gameObject.tag == "Player")
justComeOut = true;
inArea = false;
StartCoroutine(Wait());
}
IEnumerator Shoot()
{
Debug.Log("INAREA IS " + inArea + "JUSTCOMEOUT" + justComeOut);
if (inArea == true && justComeOut == false)
{
Transform clone = Instantiate(laser, transform.position, transform.rotation) as Transform;
yield return new WaitForSeconds(timeToWait);
StartCoroutine(Shoot());
}
}
IEnumerator Wait()
{
yield return new WaitForSeconds(3);
justComeOut = false;
}