Hello everyone. I got a problem and need a lead way to solve it. In my scene, there are two enemies. Player is behind them. What I want is, if player fires his rifle, enemies will hear it and turn and shoot player. I made a enemy AI code, and deactivated it. If it’s active, enemies will start firing at us immediately. So what I need to do is, activate the enemy AI code and apply an animation to enemy AI for realistic “hearing bullet sound” effect when player fires. I made a code like this :
#pragma strict
static var isFired : boolean = false; // this is true when player shoots
function Update () {
Find();
}
function Find() {
if(isFired) {
var enemies : GameObject[];
enemies = GameObject.FindGameObjectsWithTag("Enemy"); // detect those two enemies
for ( var enem : GameObject in enemies)
{
if(enem){ // if there is any object in enemies array in the scene
enem.animation.Play("lookAround");
yield WaitForSeconds(1);
enem.GetComponent(aiDuran).enabled=true; // enable the AI code
}
isFired=false;
}
}
}
So this code works fine if I fire to somewhere in the scene. They play their look around animations and then their AI becomes activated and they shoot. But if I directly fire at enemy to kill, after the enemy is dead it gives an error. It says : The object of type GameObject has been destroyed but you are still trying to access it. And when I click the error it shows this line :
enem.GetComponent(aiDuran).enabled=true;
What I understand is, I fire, isFired becomes true, while code waits for 1 second, the enemy becomes dead ( my weapons damage is high kills instantly the enemy ) and then when it comes this line :
enem.GetComponent(aiDuran).enabled=true;
it gives error because the enemy is already dead and destroyed itself. If I change the code like this :
static var isFired : boolean = false; // this is true when player shoots
function Update () {
Find();
}
function Find() {
if(isFired) {
var enemies : GameObject[];
enemies = GameObject.FindGameObjectsWithTag("Enemy"); // detect those two enemies
for ( var enem : GameObject in enemies)
{
if(enem){ // if there is any object in enemies array in the scene
enem.GetComponent(aiDuran).enabled=true;
}
isFired=false;
}
}
}
everything works fine, but it looks ridiculous because the enemy starts firing at the same time we fire, there is no animation and it looks bad. I don’t want it, how can I fix the problem ? Thanks