Let's say I have the following structs:
using System;
using System.Collections.Generic;
protected struct Inventory
{
private struct InventorySlot
{
public InventorySlot(int numItems, int containsId)
{
NumItems = numItems;
ContainsId = containsId;
}
public int NumItems { get; private set; }
public void AddItem()
{
NumItems += 1;
}
public void DeleteItem()
{
NumItems -= 1;
}
}
private int NumSlots;
private List<InventorySlot> InventorySlots { get; set; }
public Inventory(int numSlots)
{
NumSlots = numSlots;
InventorySlots = new List<InventorySlot>(NumSlots);
}
public void AddItem(int ItemId)
{
if (InventorySlots.Exists(slot => slot.ContainsId == ItemId))
{
InventorySlot insertSlot = InventorySlots.FindLast(slot => slot.ContainsId == ItemId);
insertSlot.AddItem();
}
else
{
InventorySlots.Add(new InventorySlot(1, ItemId));
}
for (int i = 0; i < InventorySlots.Count; i++)
{
print("inventorySlot " + i + ":" + InventorySlots[i].NumItems);
}
}
public void DeleteItem(int inventorySlotIndex)
{
try
{
InventorySlots[inventorySlotIndex].DeleteItem();
}
catch (Exception ex)
{
throw new Exception("Fehler beim Löschen eines Items: " + ex.Message);
}
}
}
Then I expect the following code to increase/decrease PlayerInventory.InventorySlots[0].NumItems
by 1. after it creates the first InventorySlot List entry.
private Inventory PlayerInventory = new Inventory(9);
public void AddDelete()
{
PlayerInventory.AddItem(ItemId: 1);
PlayerInventory.DeleteItem(inventorySlotIndex: 0);
}
My problem is as following: Every time I call either Inventory.AddItem()
or Inventory.DeleteItem()
the code enters the corresponding function of InventorySlot, changes NumItems but when it returns, NumItems equals 1 again. What am I missing?