- Home /
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.
Answer by Casiell · Apr 14, 2020 at 05:54 PM
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
Thanks for the quick reply I appreciate it! It's good to know I was kind of on the right track, I just felt like casting was a dirty fix. I'll check out pattern matching, thanks again hope you have a great day!
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
Scriptable object problems 1 Answer
Accessing a specific scripableobject index that can spawn from a single prefab 0 Answers
Attach a non Monobehavior class to a GameObject 1 Answer
How to prevent an inherited variable from showing up on a scriptable object? 1 Answer