Enemy script stops working after the first group of enemies
I working on a game where a player works her way through a dungeon killing monsters.(Super original, right?) There are about 20 different rooms in the main scene and each room has 3-6 monsters in it. Right now, they cast a Ray on the player when she is within a certain range, but if the ray hits a wall/door they stay idle until the ray hits her. That way they will only attack when she enters their room. It is working for the first room that I enter but not any of the next rooms. When I start at a different room, it'll work for that room and then not the others again. So it appears that the code is getting stuck and only playing for the first group of enemies I encounter. Any thoughts on how I can avoid this? This is the movement code that all the enemies run.
// Update is called once per frame
void Update () {
if (!GameMgr.instance.GameOver && enemyHealth.IsAlive) { //game going, enemy alive
if (Vector3.Distance (transform.position, player.transform.position) < aggroRange && !setAttack) {
//Check for aggro
print ("In range, attack not set");
anim.Play("Idle");
SightCheck ();
} else if (Vector3.Distance (transform.position, player.transform.position) < aggroRange && setAttack) {
//Execute aggro decision
print ("In range, attack set");
AttackThePlayer ();
}
} else if ((!GameMgr.instance.GameOver || GameMgr.instance.GameOver) && !enemyHealth.IsAlive) { //enemy dead
nav.enabled = false;
}else {
nav.enabled = false;
anim.Play ("Idle");
}
}
This is the sight check function to see if they have a clear line of sight to the player
//Sight Check
private void SightCheck(){
RaycastHit rayHit;
//direction the ray will travel
Vector3 rayDir = (player.position - transform.position+ new Vector3(0f,1f,0f));
//ray
Ray lineOfSight = new Ray (transform.position + new Vector3(0f,1f,0f), rayDir);
Debug.DrawRay (transform.position+ new Vector3(0f,1f,0f), rayDir, Color.red);
//if the ray hits something
if (Physics.Raycast (lineOfSight, out rayHit)) {
//if it hits a player
if (rayHit.collider.gameObject.tag == "Player") {
print ("Colliding with Player");
setAttack = true;
//if it hits anything else
} else {
print ("Not Colliding with Player");
setAttack = false;
anim.Play ("Idle");
}
}
}
And then the attack function(which I really think I could just put in the IF statement above, but this sorta works so I haven't changed that.)
//Attack the player
private void AttackThePlayer(){
anim.SetBool ("InSight", true);
nav.SetDestination (player.position);
}