A Unity example demonstrating the Strategy Pattern with a combat system.
The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. In this example, we use it to implement different attack strategies that a character can switch between during gameplay.
IAttackStrategy.cs
: Base interface for all attack strategiesCharacter.cs
: Context class that uses the strategies- Strategies:
MeleeAttackStrategy.cs
: Close-range attackRangedAttackStrategy.cs
: Long-range attackAreaAttackStrategy.cs
: Area-of-effect attack
// Add Character component to a GameObject
Character character = gameObject.AddComponent<Character>();
// Switch between different attack strategies
character.SetAttackStrategy(new MeleeAttackStrategy());
character.SetAttackStrategy(new RangedAttackStrategy());
character.SetAttackStrategy(new AreaAttackStrategy());
// Perform attack with current strategy
character.PerformAttack();
- Easy to add new attack strategies
- Switch strategies at runtime
- Clean separation of attack algorithms
- Encapsulated attack behavior