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

Optimizing Object Interactions with the Strategy Pattern

You will encapsulate interchangeable algorithms within separate classes, allowing you to swap behaviors like AI movement or combat logic at runtime.

In this lesson, you will learn how to use the Strategy Pattern to decouple complex behaviors from your game objects, allowing you to swap logic dynamically at runtime.

The Strategy Pattern Explained

In Unity, we often end up with bloated scripts full of if-else or switch statements to handle different states, like an enemy that changes its movement style based on its health. This violates the Open-Closed Principle. The Strategy Pattern solves this by encapsulating specific algorithms (strategies) into their own classes, which your primary object can then "use" as needed.

Instead of writing a hardcoded movement script, you define an interface that represents the action. Your main character component simply calls a method on an assigned strategy object, without needing to know the details of how that movement is calculated.

Practical Implementation

First, define an interface for the behavior:

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

Next, create concrete implementations:

public class AggressiveMovement : IMovementStrategy {
    public void Move(Transform transform) { /* Rush player logic */ }
}

public class PatrollingMovement : IMovementStrategy {
    public void Move(Transform transform) { /* Waypoint loop logic */ }
}

Finally, your EnemyController doesn't need to know how to move; it just holds a reference to the interface:

public class EnemyController : MonoBehaviour {
    private IMovementStrategy _movementStrategy;

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

    void Update() {
        _movementStrategy?.Move(transform);
    }
}

Why This Matters for Optimization

By swapping out strategy classes at runtime, you avoid expensive checks or massive class hierarchies. This makes your systems modular, easier to unit test, and highly performant, as you only execute the specific logic required for the current state rather than parsing through complex conditional logic in every frame. You are now treating behaviors as interchangeable assets rather than rigid, baked-in instructions.

Key Takeaway: The Strategy Pattern empowers you to define a family of algorithms, encapsulate each one, and make them interchangeable, allowing your objects to adapt their behavior dynamically without modifying their base structure.