My game features two types of items: weapons and consumables. They share enough features (fields: prefab, name, description, icon, value, etc; methods: use, equip, discard, sort, etc) that it would make sense for them to derive from the same abstract Item base class (which itself derives from ScriptableObject). Their gameplay purposes are however distinct enough to warrant two different inventories, be it only because they have different management interfaces; I might also want consumables but not weapons to be stackable, or carrying limit to be infinite for weapons but not consumables ā that kind of thing. And maybe later, I might even want a Talisman inventory or a Key inventory to boot.
Now I have a TreasureChest class; all that is required is to drag ānā drop an Item in the Inspector field, which thanks to polymorphism could be any class deriving from Item i.e. a weapon OR a consumable. The player interacts with the chest, and the item is returned to them. And this is where Iām a bit troubled: Iād like to devise some system which is able to determine what type of item was obtained and put it in the matching inventory, and Iām not quite sure how to go about it. After all, treasure chests can contain any type of items and TreasureChest therefore returns an Item (the base class) rather than one of the specific classes deriving from it.
My Inventories class contains two instances (one for each item type) of the Inventory class, which is centered around a List and contains all sorts of methods that pertain to adding, removing and sorting items in that List. That means I can easily create new inventories if need be, but it also means any inventory could technically hold any kind of item regardless of function. I could make the Inventory class an abstract base for specific inventories much like items, but then Iād lose the versatility that allows me to to easily create new inventories; every item type would need its matching inventory type.
What Iām using right now is a convoluted type check: the item returned from the chest is handled by a method in my Inventories class that determines which exact child class the item is an instance of (i.e. if returnedItem is ConsumableItem, etc) and then adds it to the appropriate inventory. It works, but rubs me the wrong way: Isnāt the whole point of abstract base classes to⦠abstract from particulars and eliminating the need to check for specifics? I believe there is a fundamental architectural flaw in my current approach and Iād greatly appreciate some assistance from more experienced programmers. Cheers!