Skip to main content

Enemy AI: Chase a player

This example will have an enemy player chase a player object.

An example of an enemy chasing a player (with a spawn point created) can be found here.

It assumes that you already have a player prefab and an enemy prefab created.

Setup your level / environment with the enemy object (with no scripts)

Add your player with movement of your preference.

Add the AI Navigation panel through Window > AI > Navigation

This adds the Navigation panel.

On the agents tab you can set the radius and height of the agent. More useful is setting the step height which is how high the object can step up and the Max slope which is the angle surface the object can move up.

Now we need to create an area that the object will be able to move around.

Select the Object tab and then Mesh Renderers

We can now see all of the meshes in the scene.

Select all of the meshes you want to be walkable.

Make sure the static box is checked.

Switch to the Bake tab.

Click the Bake button

You should now have a light blue area shown. This is the area that the enemy AI agent (or any agent) will be able to walk on. The smaller white areas are the parts it cannot get to.

Select the enemy object and return to the inspector view.

Add the NavMesh Component.

Now we need to add code to our enemy object.

Create a script EnemyTargetPlayer and attach it to the object.

Open the script.

Add the code below

  1. This imports the AI package to handle pathfinding
  2. This is a variable to store the target position of the object we want to move the agent towards. In this case it is the player.
  3. Is a variable for the nav mesh agent so that we can pass it the target location and move the object towards it
  4. This will get the NavMeshAgent component that is attached to this game object and assign it to the variable agent.
  5. We want the object to update its target position every frame in case the target object moves.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 1. Use the AI package to manage AI pathfinding on navmeshs
using UnityEngine.AI;

public class EnemyTargetPlayer : MonoBehaviour
{
// 2. The target for the object to move towards
public Transform targetPosition;
// 3. The navmesh agent
NavMeshAgent agent;

// Start is called before the first frame update
void Start()
{
// 4. Get the navmesh agent attached to this gameobject
agent = GetComponent<NavMeshAgent>();
}

// Update is called once per frame
void Update()
{
// 5. Every frame update the targetPosition of the agent (in case it moves)
agent.SetDestination(targetPosition.position);
}
}

Save and return to Unity.

Drag the player object into the targetPosition box of the script.

Test your scene.

You should have the enemy object moving towards the player object no matter where the player object is.