- Home /
Suggestions on the best way to handle an inventory system? [Adding, removing, best practice]
Hey guys I have a inventory system that takes in item classes, the current way I have implemented it is to have the amount of items I can store by weight (Omitted unnecessary code):
public class Inventory
{
public Dictionary<item, int> inventory = new Dictionary<item, int>();
public void InventoryAdd(Item item)
{
if (inventory.ContainsKey(item))
inventory.Add(entity, inventory[item] += 1);
else
inventory.Add(item, 1);
}
public void InventoryRemove(Item item, int amount)
{
if(inventory.ContainsKey(item) && amount <= inventory[item])
{
inventory[item] -= amount;
//Don't NEED this but I am just removing the item for now. I need to check the cost trade offs
if (inventory[item] == 0)
inventory.Remove(item);
}
}
}
This is what I have implemented, but it's not really what I am looking for. I don't really like the idea of removing from a dictionary every time the user sets it to 0. I could keep a 0 index in the dictionary and check on the other side if it's greater and only display when greater, but that could leave me open to other problems seeing how I don't know how many items I am going to have seeing how people can craft their own items.
So I am torn between removing a key/value or having multiple inventories (Unlimited) with (Unlimited) empty indexes.
Any suggestions on how I could make this better? Or any suggestions on what you would do instead? Always looking to improve,
Thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220612103937im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Array index is out of range? 1 Answer
How to go around creating inventory with new GUI (4.6 Beta)? 1 Answer
How can I display a ScriptableObject as a list inGame? 1 Answer
Make a event trigger raycast ignore a layer 1 Answer
Struggling with part of my crafting-algorithm and don't know what my mistake is 1 Answer