Hi,
I’m currently writing an inventory system for my game in unity and i have a little problem concerning the array in which i save my items.
To store my items in the inventory i unite items of the same type into an item stack and then i store the item stack into an one dimensional array.
The ItemStack class is a standard class which derives from nothing and my Inventory is a MonoBehaviour class and contains the array.
Here is the simplified code:
The ItemStack class basically contains the item which is stored in the stack and the amount.
public class ItemStack
{
private Item stackItem;
private int stackSize;
public ItemStack(Item item, int amount)
{
stackItem = item;
stackSize = amount;
}
public ItemStack()
{
stackItem = null;
stackSize = -1;
}
}
The Inventory class holds the array:
public class Inventory : MonoBehaviour
{
public ItemStack[] inventory = new ItemStack[20];
}
To add a stack to the inventory i do following:
public bool StoreInFirstFreeSlot(Item item)
{
for (int i = 0; i < inventorySize; i++)
{
if (inventory *== null)*
{
ItemStack stack = new ItemStack(item, 1);
inventory = stack;
return true;
}
}
return false;
}
Until here everything is fine. I initialize a new ItemStack and give it the item and the amount. Right after that line the item in the item stack is not null. But when i want to access the Stack later on it says that the item in the stack is null. But i can still access the methods and values of the item.
Why is the item null when i want to access it later ? I know that an object can be fake null but why is the variable stackItem even deleted or set to null in the itemStack class ?