In this lesson, you will learn how to encapsulate AI behaviors into individual classes to move away from bulky, error-prone switch or if-else statements in your enemy scripts.
The Problem with Monolithic AI
When you build AI, you often start by putting logic for patrolling, chasing, and attacking all inside one EnemyController script. This leads to a "God Object"—a script that is difficult to read, impossible to test in isolation, and prone to breaking whenever you add a new behavior. By applying the Single Responsibility Principle, we can break these behaviors into distinct, encapsulated classes.
Encapsulating Behaviors
Instead of a monolithic script, create a base EnemyState class and derive specific behaviors from it. Each class handles its own entry logic, update logic, and exit criteria. This keeps your code modular: if you want to change how an enemy patrols, you only touch the PatrolState class, leaving the rest of the AI logic untouched.
Here is a simplified example of how you might structure an encapsulated state:
public abstract class EnemyState {
protected NavMeshAgent agent;
public abstract void OnUpdate();
}
public class PatrolState : EnemyState {
public override void OnUpdate() {
// Logic for moving between waypoints
}
}
public class ChaseState : EnemyState {
public override void OnUpdate() {
// Logic for following the player
}
}
Why this is better
By encapsulating state logic, your EnemyController no longer needs to know how to patrol or how to chase. It simply holds a reference to the current EnemyState and calls currentState.OnUpdate(). This decoupling allows you to swap behaviors at runtime—such as switching from PatrolState to ChaseState when the player enters a trigger zone—without the "spaghetti code" of nested conditional statements. This structure makes your AI system highly extensible; if you want to add a "FleeState" later, you simply create a new class without modifying your existing, battle-tested patrol or chase logic.
Key Takeaway: Encapsulating state logic into individual classes transforms complex, rigid AI scripts into a flexible library of modular behaviors that are easier to debug, extend, and maintain.