- Home /
unity3d simple inventory
So I'm making a game with an inventory, but the AddItem function i've made, does not work properly. When I add an item, it adds the first and the second item, but if I then wan't to check if the ID of what I've picked up, is the same as an item I already have in my inventory, and then add an amount to the total amount, it doesn't work.
After I added, say wood. I can add multiple wood items, and it will work perfectly. but if I add another item like stone, I can add 1, then it will create a new inventory slot, every time I pick up a stone, but at the same time add the given amount to the total amount of every single inventory slot with the given ID...
The Code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Inventory : MonoBehaviour {
//Privates
private ItemDatabase database;
//Lists
public List<Item> inventory = new List<Item>();
// Use this for initialization
void Start () {
database = GameObject.FindGameObjectWithTag("ItemDatabase").GetComponent<ItemDatabase>();
}
public void AddItem (int id, int amt) {
if(inventory.Count == 0)
{
inventory.Add(database.items[id-=1]);
inventory[0].itemAmt = amt;
}
else
{
print("We have more than 0 inventory slots");
for(int i = 0; i < inventory.Count; i++)
{
if(inventory[i].itemID == id)
{
print("We already have 1 of theese items in our inventory");
inventory[i].itemAmt += amt;
break;
}
else if(inventory[i].itemID != id)
{
print("We didn't have any of these items in our inventory");
inventory.Add(database.items[id -= 1]);
inventory[i+=1].itemAmt += amt;
break;
}
}
}
}
}
because your loop goes over the first object, if its not in the list it goes straight to the else if, that way it adds a new one for every stone for example.
Answer by ShadyProductions · Jan 02, 2016 at 08:16 PM
private int existingSlot;
bool doesExist(int ID) {
for(int i = 0; i < inventory.Count; i++) {
if (inventory[i].itemID == ID) {
existingSlot = i;
return true;
}
}
existingSlot = inventory.Count +1;
return false;
}
public void AddItem (int id, int amt) {
if(inventory.Count == 0) {
inventory.Add(database.items[id-=1]);
inventory[0].itemAmt = amt;
} else {
if (doesExist(id)) {
print("We already have 1 of these items in our inventory");
inventory[existingSlot].itemAmt += amt;
} else {
print("We didn't have any of these items in our inventory");
inventory.Add(database.items[id -= 1]);
inventory[existingSlot].itemAmt += amt;
}
}
}
Here we go.
Your answer
Follow this Question
Related Questions
Issues with Inventory script 0 Answers
Multiple Cars not working 1 Answer
Decorator pattern for inventory item class 0 Answers
Distribute terrain in zones 3 Answers
Count object list duplicates 1 Answer