- Home /
Add to element quantity value if it already exists
Hello! So I'm trying to make a simple inventory system here that stores the tiles I have, their quantity, name, and description. So far I've made it so that they add together pretty well, but it only works on the first tile that I pick up. All the other tiles that I pick up are added as separate elements, as the computer can't seem to detect that they are in the list.
public bool itemAlreadyExists;
public int existingItem;
public void addTile(int itemID) {
// check to see if tile already exists in list, then only add to its quantity
GameObject newTile = database.tiles [itemID];
for (int i = 0; i < items.Count; i++) {
if (items [i]._item == newTile) {
itemAlreadyExists = true;
existingItem = i;
print (itemAlreadyExists);
break;
} else {
itemAlreadyExists = false;
print (itemAlreadyExists);
break;
}
}
print (existingItem);
if (itemAlreadyExists == false) {
items.Add (new Item_Class {
_item = newTile,
_name = newTile.name,
_description = newTile.GetComponent<BlockProp> ().description,
_quantity = newTile.GetComponent<BlockProp> ().quantity,
_type = 0
});
} else if (itemAlreadyExists == true) {
items [existingItem]._quantity += 1;
}
do something like this : bool checkIfItemInInventory(Item item) { for (int i = 0; i < items.Count; i++) { if (items [i].itemID== item.id) { return true;
} } return false; }
Thanks - that got me started in the right direction. The code I created based on yours is almost perfect. It'll only work for the first block I pick up (adding the integers together), after that, any other blocks that I pick up are added as separate elements, not being combined. GameObject newTile = database.tiles [itemID];
for (int i = 0; i < items.Count; i++) {
if (items [i]._item == newTile) {
itemAlreadyExists = true;
existingItem = i;
print (itemAlreadyExists);
break;
} else {
itemAlreadyExists = false;
print (itemAlreadyExists);
break;
}
}
print (existingItem);
if (itemAlreadyExists == false) {
items.Add (new Item_Class {
_item = newTile,
_name = newTile.name,
_description = newTile.GetComponent<BlockProp> ().description,
_quantity = newTile.GetComponent<BlockProp> ().quantity,
_type = 0
});
} else if (itemAlreadyExists == true) {
items [existingItem]._quantity += 1;
}