Esempio n. 1
0
    /// <summary>
    /// Method to take out 1 or more items of a specific type from the inventory space.
    /// The method will make sure to take things from the stack that has the least number
    /// of items first.
    /// Returns an InventoryItem with at most count items in it.
    /// </summary>
    /// <param name="toTake"></param>
    /// <param name="count">Max number of items to take, defaults to 1.</param>
    /// <returns></returns>
    public InventoryItem Take(InventoryItem itemStack, uint count = 1)
    {
        if (!isAccessible)
        {
            return(itemStack);
        }

        // List of item stacks to hold potential sources.
        List <InventoryItem> stacks = new List <InventoryItem>(Mathf.FloorToInt((float)count / InventoryItem.MaxStackSize) + 1);

        // Loop through the inventory to find the stacks.
        foreach (InventoryItem item in items)
        {
            if (item._item == itemStack._item)
            {
                stacks.Add(item);
            }
        }

        // If none, return empty inventory item.
        if (stacks.Count == 0 || count == 0)
        {
            return(itemStack);
        }

        // Now sort by item count if we need to.
        if (stacks.Count > 2)
        {
            stacks.Sort(InventoryItem.SortByCountAsc);
        }
        else if (stacks.Count > 1)
        {
            if (stacks[0].count > stacks[1].count)
            {
                stacks.Reverse();
            }
        }

        // Now take items from the stacks, starting with the smallest stack.
        foreach (InventoryItem stack in stacks)
        {
            if (itemStack.CanStackWith(stack))
            {
                TransferItemsOut(stack, itemStack, count);
                if (itemStack.count >= count)
                {
                    break;
                }
            }
        }

        return(itemStack);
    }