Skip to main content
Unity 3D Basics – Complete Beginner to Advanced Guide
CHAPTER 11 Beginner

Enemy AI and NPC Basics

Updated: May 16, 2026
35 min read

# CHAPTER 11

Enemy AI and NPC Basics

1. Introduction

If the player runs behind a wall, a dumb enemy will keep walking forward, constantly smashing its face into the bricks. A smart enemy will dynamically calculate the shortest path *around* the wall, up the stairs, and jump down behind the player. Writing pathfinding math from scratch is incredibly difficult, but Unity provides a built-in, AAA-quality artificial intelligence system: the NavMesh (Navigation Mesh). In this chapter, we will master Enemy AI and NPC Basics. We will learn how to bake a NavMesh into our level, configure the NavMeshAgent component, and write C# scripts to create intelligent patrol routes and relentless chase behaviors.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Explain what a Navigation Mesh (NavMesh) is.
  • "Bake" a NavMesh onto your 3D level geometry.
  • Apply and configure a NavMeshAgent component to an enemy.
  • Write C# code to command an agent to chase a moving target.
  • Implement a basic waypoint patrol system.

3. The NavMesh (The Blue Walkway)

The NavMesh is an invisible blue grid that Unity calculates and paints over your floors, ramps, and stairs. It tells the AI: *"You are allowed to walk here. Do not walk off this cliff. Do not walk through that solid wall."*
  1. 1. Go to Window -> AI -> Navigation.
  1. 2. Select your floor and walls in the Hierarchy. In the Navigation window (Object tab), check Navigation Static.
  1. 3. Go to the Bake tab and click Bake.
  1. 4. You will see a blue overlay appear on the floor. The AI can now navigate your world!

4. The NavMeshAgent (The AI Brain)

To make an enemy use the NavMesh, you attach a NavMeshAgent component to it.
  • This component replaces standard Rigidbodies for movement. It handles its own gravity, collision avoidance (steering around other enemies), and velocity.
  • You can tune its Speed, Angular Speed (how fast it turns), and Stopping Distance.

5. Chasing the Player (C# Logic)

Commanding an AI to move is stunningly simple. You do not need to calculate vectors or distances; you just give it a destination!
csharp
123456789101112131415161718192021
using UnityEngine;
using UnityEngine.AI; // REQUIRED for AI code!

public class EnemyChase : MonoBehaviour
{
    public Transform player;
    private NavMeshAgent agent;

    void Start()
    {
        // Grab the brain
        agent = GetComponent<NavMeshAgent>();
    }

    void Update()
    {
        // Constantly update the destination to wherever the player is right now.
        // The Agent automatically calculates the path around walls!
        agent.SetDestination(player.position);
    }
}

6. Patrolling with Waypoints

If the player is hiding, the enemy should patrol the area.
  • We create empty GameObjects in the scene to act as invisible "Waypoints".
  • The AI script holds an Array (a list) of these waypoints.
  • It tells the agent to go to Waypoint 0. When agent.remainingDistance is near 0, it tells the agent to go to Waypoint 1, and so on.

7. Combining States (Basic AI Brain)

A true AI uses conditions to switch between behaviors.
  • Use Vector3.Distance(transform.position, player.position) to check how far away the player is.
  • If distance is > 10, run the Patrol code.
  • If distance is <= 10, run the Chase code!
*This is the foundation of a State Machine.*

8. Visual Learning: NavMesh Pathfinding

txt
1234567
[ Enemy ]                      [ Player ]
    \                          /
     \                        /
      \___ [ Solid Wall ] ___/
           [ NavMesh Hole ]
           
*The NavMeshAgent knows it cannot walk through the hole where the wall is, so it automatically generates a path AROUND the wall to reach the player.*

9. Best Practices

  • NavMesh Obstacles: If you have a moving object in your game (like a physics crate the player can push), it wasn't baked into the static NavMesh. Enemies will try to walk through it. Attach a NavMeshObstacle component to the crate and check the Carve box. This tells the AI to dynamically cut a hole in the NavMesh wherever the crate moves, forcing enemies to walk around it in real-time!

10. Common Mistakes

  • Baking Moving Floors: The NavMesh can only be baked on objects marked as "Static" (objects that will never move). If you bake a NavMesh onto an elevator or a moving platform, the blue grid will stay floating in the air when the elevator moves down, and the AI will walk right off the edge! Moving AI platforms requires complex dynamic NavMesh scripts.

11. Mini Project: Create an Enemy Chase System

Objective: Build an intelligent zombie that navigates a maze to find you.
  1. 1. Build a simple maze using 3D Cubes.
  1. 2. Mark the floor and the maze walls as Navigation Static, then hit Bake in the Navigation window. (Ensure you see the blue floor).
  1. 3. Create a Capsule named "Player" and place it at one end.
  1. 4. Create a red Capsule named "Zombie" at the other end.
  1. 5. Add a NavMeshAgent component to the Zombie. Change its speed to 3.5.
  1. 6. Create the EnemyChase.cs script (from Section 5) and attach it to the Zombie.
  1. 7. Drag the Player into the script's target slot.
  1. 8. Press Play and move the Player around. Watch the zombie navigate the maze perfectly to reach you!

12. Practice Exercises

  1. 1. What specific component must be attached to an enemy character so it can utilize the baked pathfinding data?
  1. 2. What using namespace must be added to the top of your script to gain access to the NavMesh classes?

13. MCQs with Answers

Question 1

Before an AI enemy can calculate a path across your level, what mandatory step must you perform in the Unity Editor?

Question 2

An enemy is chasing a player using agent.SetDestination(player.position). The player runs behind a locked door, and the enemy runs straight into the door repeatedly. Why?

14. Interview Questions

  • Q: Explain the relationship between a baked NavMesh and a NavMeshAgent. How does this system save the CPU from performing heavy pathfinding calculations every frame?
  • Q: Describe how you would build a basic AI State Machine in C# that transitions an enemy from a "Patrol" state to a "Chase" state when the player gets within 15 meters.
  • Q: What is a NavMeshObstacle? Contrast its usage with a static baked obstacle, and provide a gameplay example where a NavMeshObstacle with "Carving" enabled is required.

15. FAQs

Q: Can I use the NavMesh for a 2D game? A: Unity's built-in NavMesh system is primarily designed for 3D X/Z plane movement. For 2D top-down games, you usually need to use a specialized 2D pathfinding package (like the free A* Pathfinding Project) or use the experimental NavMeshPlus 2D package.

16. Summary

In Chapter 11, we gave our game a brain. We explored the massive power of the NavMesh system, learning how to bake static geometry into a walkable blue grid. We attached the NavMeshAgent component to our enemies, allowing the engine to handle collision avoidance and path calculations automatically. Finally, we wrote simple, highly effective C# scripts to command the agent to chase the player dynamically and patrol between invisible waypoints.

17. Next Chapter Recommendation

Our level has a player, enemies, and UI. But what happens when the player beats the level? Proceed to Chapter 12: Scene Management and Game Flow.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·