Problem Enemy ai still moves to the player after it dies

When I kill my enemy ai far away it stills moves up to the player even when its dead. I want the enemy ai to stay where it at when it die. Not move to the player after it dies. What might be the problem ?

Just check the player health before doing anything in Enemy AI , if you couldn’t solve the problem paste you AI here.

Your problem most probably consists of you storing the players transform.position as a Vector3 in you AI Script and updating and moving towards it every frame. Alternatively, you are using the built-in NavMesh agent and not stopping it upon the players death.
In either cases, when the player dies, the target position of the AI Script/Agent is not updated anymore (as the player’s transform is null).

The problem: The AI script continues moving because the target Vector3 is not null. It merely contains the players final position before his death.
In some games, where enemies for some reason want to reach the player’s corpse - to for example steal something from him after he dies, this behavior is desired.

If this behavior is not wanted, there are several ways to solve this:

  • If the player’s GameObject is destroyed, you should make the enemy AI script check if the player GameObject still exists, and if not set the target Vector3 to it’s own position. That way it will immediatly reach it’s destination and stop moving.

  • When using the built-in NavMeshAgent, upon player death stop all NavMeshAgents from moving by doing something like this:

    void Die(){
    GameObject enemies = GameObject.FindGameObjectsWithTag(“Enemy”);
    foreach(GameObject enemy in enemies){
    NavMeshAgent agent = enemy.GetComponent();
    (Disclaimer: Code above was not tested, it might contain spelling mistakes)

  • But again, if you use your own Enemy AI script, you can modify the above code to call a stop function which you create on all enemy AI’s.

You could solve the problem simply by modifying your code to fit in an if statement:

  void Update () 
      if (Player is alive check)
          if (Vector3.Distance(player.position, this.transform.position) < 20)
              Vector3 direction = player.position - this.transform.position;
              direction.y = 0;
 of code....

You have the transform of the player so could do something like:


as the player check, assuming you disable the player when dead.

The best way would be to use a messaging system and send a message out on player death. With this message, you can automatically stand down any AI when they receive the message. I recommend using the Advanced C# messenger if you are not already using a messaging system:

Advanced C# Messenger