Item data structure - Scriptable Object Inheritance problems

Hi all,

I’ve been racking my brain for a few days with this problem. I can’t figure out the best way of doing it, so I’ll go over my goal and what I’ve done so far.

Goal: To store items within a game in a clean data structure. All Items stem from an item scriptable object. Then there’s Weapon objects that inherit from this item class, and add a few extra variables such as damage and speed. There will be multiple object types, like the tool object which will have a few extra variables and such.

I first went around the problem by creating these structable objects, and then creating an inventory script that holds these items. However, it holds these items by having a list of itemobject. This is great and works fine, however I can’t access the child variables, for example;

I can access all the variables in the base item class, but not the sub classes. I understand this is because I’m storing a list of itemobjects. How should I be storing them?

I’ve casted to the correct class and can then access the variables there, but that doesn’t seem right as I’d end up with a if/select statement for each different sub class.

I’m pretty sure you have the right idea to do this. And you are right, you will have to cast Item to other classes, but only do that when needed! So for example your sword should only be cast to weapon when you are trying equipping it.

If you need some of the stats while in inventory (for example to have on hover popups with item stats and description) then consider delegating this responsibility to Item classes. Item could have GetTooltip method that would give you only name, but Weapon would extend that method for damage etc.

Remember, when calling a method, the override from the highest class will be called. So even if you call method X on Item, if this item is a Weapon then the Weapon.X will be called instead.

Also I recommend checking out pattern matching it’s a godsend when working with inheritance and generics.

Sorry for the answer being so chaotic, I hope you’ll get something from it nonetheless