NPC NavMeshAgent to seek or flee destination while avoiding obstacles

The introduction of Unity's NavMeshAgent has greatly simplified the coding for NPC and enemy agent behaviors. In this recipe, we'll add some wall (scaled cubes) obstacles, and generate a NavMesh, so that Unity knows not to try to walk through the walls. We then add a NavMeshAgent component to our NPC GameObject, and tell it to head to a stated destination location by intelligently planning and following a path, while avoiding the wall obstacles.

In the next screenshot, we can see in the Scene panel the squares that represent potential points on the path. We can also see lines showing the current temporary direction and destination around the current obstacle.

When the Navigation ...

Get Unity 5.x Cookbook 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.