Array --> A list of Items, each Item having a Quantity

Hi all,

I’ve always been having difficulty grasping arrays so bare with me. I’m trying to make an array that contains Items and each Item has a Quantity attached to them.

Let’s call the array Bag. In the beginning, the Bag has 1 Item and that Item has a Quantity of 5. How would I first create this?

After that, I want to be able to add new Items and a Quantity for those new Items.

In the long run, I want to be able to say “If Bag has 5 Apples, then do the following”

I hope everyone understands what I’m trying to do. If anyone can help me, please do =D

Thanks

You want hash tables

Add a key called apples then do a contains search on the table to see if the bag has the key apples

e.g.

var bag : Hashtable;
bag = new Hashtable();
bag.Add("Apple",5);
if(bag.Contains("Apple")) {
    Debug.Log("Got apples");
}

Wow, I never even heard of HashTables.

Ok… so let me try to understand this. using your example as an example, the line that reads:

bag.Add("Apple",5);

Means that in the Bag, there is an item called Apple and it has a quantity of 5?

So then if I wanted for something to happen if there are 5 Apples, I would then go:

if(bag.Contains("Apple") == 5) {
    Debug.Log("Got 5 Apples");
}

Is that correct?

Spinaljack’s way seems pretty sound. I handled it differently.

If your creating an Inventory/Bag System, Which would be my guess, Your probably going to only allow certain items to be added into your “Bag”.

A script such as “ItemInfo.cs” In that script you can have an option if the Item is stackable or not… And when you add it to the Bag you could see if the item matches other items in your bag’s names(or whatever you want to specifiy) add it to the stack or do whatever if your stack size is at max… This is how I handled mine currently. I have no stack limit but Potions will stack properly, Drop properly based on number given as well.

Cool, I’ll take a look at that script thanks

Well I prefer Arrays over hashtables though hashtables do come in handy at times :slight_smile:

I would create a base class first for the fruits:

class FruitData {

  var fruitType: String = "";
  var numberOfTheType: int = 0;

}

Then create an Array to hold the classes of fruits:

var fruitArray: Array;

fruitArray = new Array(FruitData);

After doing that you can store each property of the Fruits class through the array index:

fruitArray[0] = new FruitData();
fruitArray[0].fruitType = "Apples";
fruitArray[0].numberOfTheType = 5;

Then well you can access each property again through the Array index:

if (fruitArray[0].numberOfTheType == 5) {
   do something;
}