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

Dynamic Behavior Swapping with Strategy Pattern

Utilize the Strategy pattern to encapsulate interchangeable algorithms, allowing you to swap game entity behaviors at runtime without modifying class structures.

In this lesson, you will learn how to use the Strategy Pattern to swap an entity's complex logic at runtime without cluttering your main classes with endless if-else or switch statements.

The Strategy Pattern Concept

When an object needs to perform a task—like moving, attacking, or calculating damage—the Strategy Pattern lets you define that task as a standalone object (or "strategy"). Instead of hardcoding behavior inside your Enemy class, you delegate the work to an interface. By swapping which implementation is assigned to the Enemy at runtime, the object’s behavior changes instantly.

Think of it like a Character equipped with a "Weapon" item. You don't rewrite the character's code when they pick up a sword instead of a bow; you simply swap the IAttackStrategy assigned to them.

Implementing the Pattern

First, define an interface for your behavior:

public interface IMovementStrategy {
    void Move(Transform transform);
}

Now, create concrete versions:

public class WalkingStrategy : IMovementStrategy {
    public void Move(Transform t) => t.Translate(Vector3.forward * Time.deltaTime);
}

public class FlyingStrategy : IMovementStrategy {
    public void Move(Transform t) => t.Translate(Vector3.up * Time.deltaTime);
}

Finally, your Enemy script maintains a reference to the strategy and can swap it whenever needed:

public class Enemy : MonoBehaviour {
    private IMovementStrategy movementStrategy;

    public void SetMovement(IMovementStrategy newStrategy) {
        movementStrategy = newStrategy;
    }

    void Update() {
        // The enemy doesn't know HOW it moves, just that it does.
        movementStrategy?.Move(transform);
    }
}

By keeping logic modular, you avoid the "God Object" anti-pattern. You can switch from WalkingStrategy to FlyingStrategy based on game events (like an "EnterFlightMode" event) simply by calling SetMovement(). This makes your code highly extensible; adding a new "Teleporting" movement type only requires creating a new class that implements IMovementStrategy, leaving your existing Enemy class untouched.

Key Takeaway: The Strategy Pattern decouples behavior from your entities, allowing you to inject or swap logic dynamically while keeping your code clean and open for extension.