List of different types in C# (Inventory system)

2.1k views Asked by At

So, I'm building an inventory system in Unity3D using C# from scratch and I've faced the following problem:

I have three types of inventory objects:

Weapons, Equipments and Consumables.

So, for example:

// Weapon Class
class Weapon : Equipable
{
    public int damage
}

// Equipment Class
class Equipment : Equipable
{

    public EquipmentType equipmentType;

    public enum EquipmentType {
        Helmet,
        Armor
    }
}    

// Consumable Class
class Consumable : Item
{
    public ConsumableStat stat;
    public int factor;

    public enum ConsumableStat
    {
        Life,
        Mana
    }
}

// Equipable Class
class Equipable : Item
{
    public int durability
}

// Item Class
class Item
{
    public string name;
}

Now, player has a list as an inventory.

This list, should store Weapons, Equipments and Consumables

I've tried:

public List<T> inventory

But I receive the following error on console:

The type or namespace name `T' could not be found. Are you missing a using directive or an assembly reference?

Have searched the internet but found solutions that I don't think it's the most correct way to deal with it.

Someone already step in this issue?

What's the best way to really create a list of Generic Objects?

C# and Unity3D is new for me. I'm a experienced web developer migrating to gaming development.

Ps.: Sorry for the poor English and thanks in advance!

1

There are 1 answers

1
tophallen On BEST ANSWER

You need to declare a type when setting a list on a class, i.e. your public List<T> Inventory - in order to store all of these things in a single list, they need to have a common type or interface shared across them. I suggest either creating a shared interface or a base type. In this specific case, I think a base type makes the most sense. For Example:

public abstract Item
{
    string Id { get; set; }
    bool IsConsumable { get; }
    /* etc. or whatever you use in all your classes */
{

This way you can build your inventory list this way:

public List<Item> Inventory;

Whether or not that meets your needs, the issue you are running into is that you can't define a list that isn't of a type, and you need a shared base type across all your inventory items so that you can create a list of the lowest common denominator. Hope this helps.