I’ve got an Item class which holds the following variables: string Name, float Weight, int Value.
I’ve also got few item classes which inherit from Item such as Weapon, Armor, Food, Ingredients. They all store some variables suitable for those items (such as attack power, armor rating). I wanted to create an inventory using
List<Item> but I found out it doesn’t store Weapon, Armor, etc variables, nor can I read them via their getters.
Is there a way I can store all my items on one list so that I don’t have to create a list for each item type?
I’m a C# guy by the way.
Of course you can store all those items in the same list, but you need to cast it into the correct type before you can access specific members of the real type. That’s how it works in most OOP languages.
List<Item> myList = new List<Item>();
foreach(Item I in myList)
if (I is Weapon)
Weapon W = (Weapon)I;
W.RateOfFire = 5;
if (I is Armor)
((Armor)I).rating = 10;
That’s all plain C# and nothing Unity special. The only thing you have to be careful is that Unity can’t serialize a list or array of a base-class that contains derived classes. Unity serializes the classes by the variable type and not the actual type. As long as you use the List only at runtime to store your items there’s no problem.