Time for action – chasing the player

Our next script will control our simple chase AI. Because we are making use of the NavMesh and NavMeshAgent components, we can leave nearly all the difficult portions of pathfinding to Unity:

  1. Again, create a new script. This time name it ChasePlayer.
  2. The first line for this script simply holds a reference to the NavMeshAgent component that we set up earlier. We need access to this component in order to move the enemy.
    public NavMeshAgent agent;
  3. The last segment of code first makes sure that we have our NavMeshAgent reference and then updates our goal destination. It uses the PlayerPosition script's variable, that was set up earlier, and the SetDestination function from the NavMeshAgent. Once we tell the function ...

Get Unity Android Game Development by Example Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.