Adding Item to an Inventory.

I just can’t seem to work out how to add Items to my Inventory when it already exists and the amount i’m adding go’s over the ‘maxStack’ amount?

Code:

List FilterItems(Item newitem){

        List<Item> result = new List<Item>();

        foreach(Item item in PlayerInventory.Inventory){//For 'Item' in Player's Inventory...

            if(item.ID == newitem.ID){//If newItem's ID = the loops current items ID... 

                if((item.currentStack + newitem.currentStack) < item.maxStack){//If the current stack + newItems stack is less than the maxStack...

                    print ("Add");

                    result.Add(item);

                } else{

                    print ("Do something here!");

                }

            }

        }

        return result;

    }

 

public void AddItem(Item newItem){

        if(playerInventory.inventory.count > 0){//If there are 1 or more stacks

            List<Item> stacks = FilterItems(newItem);

            if(stacks.Count > 0){//if there are more than 1 returned items

                stacks[0].currentStack += newItem.currentStack;

            } else {//when there is no stack yet or all stacks are full

                PlayerInventory.Inventory.Add(newItem);

            }

        } else{//Item is not stackable

            PlayerInventory.Inventory.Add(newItem);

        }

    }

So basically, say i have One stack of 7 wood and i want to add 5. How would I code it to fill up the current stack and put the remaining 2 wood into a new stack?

Please ask if you need anything else?

This would be one approach.

Points to consider:

  1. itemAmount, how much of the newItem we are trying to allocate
  2. availableSpace, how much room is available in any given item slot
  3. making sure we look after any remaining itemAmount once we have finished our search

List FilterItems(Item newitem){
    int itemAmount = newitem.currentStack;
    List<Item> result = new List<Item>();
    foreach(Item item in PlayerInventory.Inventory){
        if(item.ID == newitem.ID) {
            if(item.currentStack < item.maxStack){
                int availableSpace = item.maxStack - item.currentStack;
                if (itemAmount < availableSpace) {
                    item.currentStack += itemAmount;
                    itemAmount = 0;
                }
                else {
                    item.currentStack = item.maxStack;
                    itemAmount -= availableSpace;
                }
                print ("Add");
                result.Add(item);
            }           
        }
    }
    if (itemAmount > 0) {
        newitem.currentStack = itemAmount;
        result.add(newitem);
    return result;
}