x


List doesn't hold children's variables

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.

more ▼

asked Aug 10 '11 at 07:20 PM

4illeen gravatar image

4illeen
63 33 35 38

I need to know if it's even possible, or should I just make many lists

Aug 10 '11 at 08:36 PM 4illeen
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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>();

myList.Add(new Weapon());
myList.Add(new Armor());
myList.Add(new Weapon());

foreach(Item I in myList)
{
    if (I is Weapon)
    {
        Weapon W = (Weapon)I;
        W.RateOfFire = 5;
    }
    // or 
    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.

more ▼

answered Aug 10 '11 at 10:11 PM

Bunny83 gravatar image

Bunny83
45.2k 11 49 207

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x355
x224
x134
x44

asked: Aug 10 '11 at 07:20 PM

Seen: 801 times

Last Updated: Aug 10 '11 at 10:11 PM