Course contentsShow
← Unity Game Development
Lesson 480 of 8287. Advanced Game ArchitectureFree lesson

Creating Modular AI Movement Strategies

Design a system of swappable movement strategies to switch an AI character's navigation logic between patrolling, chasing, and fleeing modes.

In this lesson, you will learn how to encapsulate movement logic into interchangeable strategy objects, allowing your AI to swap behaviors like patrolling, chasing, or fleeing at runtime without modifying the core controller.

The Strategy Pattern for AI Movement

Instead of writing a bloated Update method filled with if-else or switch statements, we decouple the execution of movement from the controller of the AI. By creating an interface (or base class) for movement, we define a contract: every strategy must provide a method to update the AI’s position.

Consider an IMovementStrategy interface:

public interface IMovementStrategy {
    void UpdateMovement(NavMeshAgent agent, Transform target);
}

By implementing this interface, you can create modular classes like PatrolStrategy, ChaseStrategy, or FleeStrategy. Your AIController then holds a reference to the current strategy, which it executes inside its own update loop:

public class AIController : MonoBehaviour {
    private IMovementStrategy currentStrategy;
    private NavMeshAgent agent;

    public void SetStrategy(IMovementStrategy newStrategy) {
        currentStrategy = newStrategy;
    }

    void Update() {
        // The controller doesn't care HOW it moves, just that it does.
        currentStrategy?.UpdateMovement(agent, targetTransform);
    }
}

Why This Architecture Scales

This approach provides true architectural decoupling. Because the AIController doesn't know the specifics of the movement logic, adding a new behavior—like a "Circling" strategy—requires only creating a new class rather than altering your existing, tested controller code.

When your AI transitions between states (like switching from PatrolState to ChaseState), your state machine simply calls SetStrategy() with the appropriate object. This clean separation ensures that your movement logic is testable in isolation and prevents the "God Object" anti-pattern where one script manages too many concerns. By keeping the interface thin and the implementations specialized, you ensure that your AI system remains flexible as your game's complexity grows.

Key Takeaway: By using the Strategy Pattern to encapsulate movement logic, you transform monolithic AI controllers into flexible systems where behaviors are swapped as easily as data, ensuring clean, modular, and maintainable code.