I am working on a game with an inventory system, but am trying to figure out the best way of doing it. I have read the post about adding WorldItems or InventoryItems to a list, which is fair enough and I figured that out myself anyway.
However, perhaps I add two SwordItems to this list (for example). I want the game to show that I have quantity 2 of these, not two individual items. What is the best way to achieve this with a List based inventory structure. I think I saw a GroupBy method, where I could GroupBy item type Sword. Is this a good way to achieve this? Or can you suggest a better alternative?
Answer
Build your inventory as a list of item stacks, and not items. Individual items (or items that cannot be stacked) are simply a stack of one. For example:
class ItemStack {
Item item;
int count;
// ...public methods here...
}
This allows you to treat your inventory as a simple homogeneous List
or similar, and also allows you the flexibility to support multiple stacks of a particular item -- for example, you can support splitting a stack of items in this system, whereas in one where you tried to GroupBy()
might get pretty cumbersome.
It will require a little more work on your part to deal with consumption of items or their removal from the stack, but it's not that big of a deal.
No comments:
Post a Comment