// private bool GetItemIndexByName(int tabIndex, string name) { // int index = this.inventory.GetItemIndexByName(tabIndex, name); // ItemInstance fetchedItem; // return this.inventory.GetItem(tabIndex, index, out fetchedItem); // } public void InsertItem(int tabIndex, ItemInstance item, int quantity) { bool itemExistsBeforeInsert; int insertedIndex = this.inventory.InsertItem(tabIndex, item, quantity, out itemExistsBeforeInsert); ItemInstance fetchedItem; if (insertedIndex > -1) { Slot desiredSlot = this.inventorySlots[tabIndex].tabInventorySlots[insertedIndex]; if (!itemExistsBeforeInsert) { desiredSlot.SetItemNameText(item.GetItemName()); } bool gotItem = this.inventory.GetItem(tabIndex, insertedIndex, out fetchedItem); if (!gotItem) { return; // if item doesn't exist, then something must be wrong... } int itemQuantity = desiredSlot.SetItemQuantity(fetchedItem.quantity); Debug.LogFormat("fetched: {0}", fetchedItem); } }
// Remove an item at an index if one exists at that index. public bool RemoveItem(int index) { if (SlotEmpty(index)) { // Nothing existed at the specified slot. return(false); } Debug.LogFormat("Removing {0}.", GetItemInfo(index)); // tabInventory[index].quantity = 0; ItemInstance item = tabInventory[index]; item.quantity = 0; itemIndexByName.Remove(item.GetItemName()); tabInventory[index] = null; return(true); }
// Insert an item, return the index where it was inserted. -1 if error. public int InsertItem(ItemInstance item, int quantity, out bool itemExistsBeforeInsert) { int index = -1; string itemName = item.GetItemName(); int stackLimit = item.item.stackLimit; itemExistsBeforeInsert = ItemExists(itemName); // If an item is in the inventory and can stack it, increase its quantity if (itemExistsBeforeInsert && CanStack(stackLimit)) { index = this.itemIndexByName[itemName]; ItemInstance desiredItem = tabInventory[index]; // If hasn't reached stack limit, increase stack quantity. if (!ReachedStackLimit(desiredItem.quantity, stackLimit)) { desiredItem.quantity += quantity; // update stack quantity Debug.LogFormat("Increased {0}'s quantity at index {1} in tab {2}.", item.GetItemName(), index, this.tabName); } else { Debug.LogFormat("Reached stack limit of {0}.", stackLimit); } } else { // Else insert the item into the next available slot for (int i = 0; i < tabInventory.Length; i++) { if (!SlotEmpty(i)) { continue; } tabInventory[i] = item; index = i; itemIndexByName.Add(itemName, i); tabInventory[i].quantity += quantity; Debug.LogFormat("Not in inventory - Inserted {0} at index {1} in tab {2}.", item.GetItemName(), index, this.tabName); break; } } // Couldn't find a free slot. return(index); }