In this lesson, you will learn how to decouple item functionality from your inventory core by merging the Command and Strategy patterns into a data-driven system.
The Problem: The "God" Inventory Class
In beginner projects, you often see an Inventory class with a massive switch statement or if/else block inside an UseItem(Item item) method. This is a maintenance nightmare. If you want to add a "Healing Potion," a "Teleport Scroll," and a "Quest Key," your Inventory class has to know the implementation details of every single one.
The Solution: Decoupled Strategies
Instead of the Inventory dictating what happens, we treat the item as a container for a Usage Strategy. By using the Strategy Pattern, we define an interface for how an item is consumed, and by using the Command Pattern, we encapsulate that usage as a discrete action.
First, define the strategy interface:
public interface IItemUsageStrategy {
void Execute(GameObject user);
}
Now, create concrete strategies, such as HealStrategy or AttackStrategy. These are simple, reusable classes that don't know anything about the inventory itself.
Finally, your ItemData (ScriptableObject) holds a reference to a strategy. When the player clicks an item, the Inventory doesn't process logic; it simply executes the command:
[CreateAssetMenu]
public class ItemData : ScriptableObject {
public IItemUsageStrategy usageStrategy; // Injected or assigned strategy
public void Use(GameObject user) {
usageStrategy?.Execute(user);
}
}
Why this is Modular
Because the logic is encapsulated in the strategy, you can swap behaviors at runtime. For example, a "Cursed Potion" could swap its strategy from HealStrategy to DamageStrategy after a certain condition is met, without ever touching the Inventory code.
By injecting the user context (the GameObject) into the Execute method, your strategies remain completely decoupled from the system that triggered them. This allows you to add hundreds of unique item effects simply by creating new ScriptableObject assets with different strategy assignments.
Key Takeaway: By treating item effects as interchangeable strategies triggered by commands, you transform your inventory from a rigid switch-statement controller into a flexible, data-driven engine that is infinitely scalable.