Strategy
What Is It?
Strategy is a behavioral design pattern that lets you define a behavior or algorithm in separate classes and switch between them when needed. The basic idea is simple: if there is more than one way to do the same task, each way can be written as a separate strategy, and the main class only uses the selected strategy.
For example, in Unity, a character's attack type can change: sword attack, bow attack, or magic attack. The character itself stays the same; only the attack strategy changes. The main class, called the Context, does not need to know how each attack works. It only calls the common interface it holds.
This makes the code cleaner and easier to extend without relying on long if-else or switch blocks. When you want to add a new behavior, you can simply create a new strategy class instead of changing the existing system.
When Is It Used?
Strategy is used when the same behavior has different versions and you need to switch between these versions at runtime. It is especially useful in game development.
In Unity, it can be used for situations such as:
- Enemy AI behaviors: patrolling, attacking, escaping.
- Different weapon types: sword, bow, magic, automatic weapon.
- Character movement types: walking, running, jumping, swimming.
- Different input systems: keyboard, gamepad, touch screen.
- Running the same operation with different algorithms.
In general, if you see if-else or switchblocks growing inside a class, Strategy might be a good solution. However, if there are only two simple options and the system is unlikely to grow, using Strategy may add unnecessary complexity.
Animation
Code
using UnityEngine;
namespace Patterns.Behavioral.Strategy
{
public interface IAttackStrategy
{
void Attack(Transform origin, LayerMask targetMask);
}
}Advantages and Disadvantages
• Advantages:
- It makes the code cleaner and easier to expand.
- New behaviors can be added without changing old code.
- Strategies can be tested independently.
• Disadvantages:
- It can create too many classes in simple systems.
- Too many strategies can be hard to track.
- Sharing too much data can complicate the interface design.
Tips
When using Strategy in Unity, it is often better to write strategies as plain C# classes. Most strategies do not need Unity's MonoBehaviour lifecycle.
Defining strategies as ScriptableObjects can also be very useful. This allows you to assign strategies from the Inspector, share them between prefabs, and let designers test behaviors without touching the code.
When changing strategies, it is important to handle the exit logic of the old strategy and the entry logic of the new one. Otherwise, unexpected bugs can appear.
You should also be careful with null strategies. A default strategy or a Null Object style strategy can help prevent runtime errors.
Finally, avoid creating new strategy objects every frame. A better approach is to create them beforehand and switch between them when needed.