This is the code for the add function for my inventory system that I am working on.
public void AddItem1(GameObject item, int amount)
{
for (int i = 0; i < slots.Count; i++)
{
if (slots[i].childCount > 0)
{
InventoryItem slottedItem = slots[i].GetChild(0).gameObject.GetComponent<InventoryItem>();
InventoryItem pickupItem = item.GetComponent<InventoryItem>();
//Increase same item ammount if in inventory and less than the item's max stack
if (slottedItem.itemData.ID == pickupItem.itemData.ID)
{
if (slottedItem.amount + amount <= slottedItem.itemData.maxStack)
{
slots[i].GetChild(0).GetComponent<InventoryItem>().amount += amount;
break;
}
else //{ Debug.Log("Stack Is Full"); }
if (slottedItem.amount + amount > slottedItem.itemData.maxStack && slottedItem.amount != slottedItem.itemData.maxStack)
{
int amountOverMax;
int remainder;
amountOverMax = slottedItem.amount + amount - slottedItem.itemData.maxStack;
remainder = slottedItem.itemData.maxStack - slottedItem.amount;
//If there is an amount over max stack, create a new stack and add to it, as well as add the remainder to previous stack
slots[i].GetChild(0).GetComponent<InventoryItem>().amount += remainder;
for (int x = 0; x < slots.Count; x++)
{
if (isFull[x] == false)
{
Instantiate(item, slots[x]);
slots[x].GetChild(0).GetComponent<InventoryItem>().amount += amountOverMax - 1;
CheckSlots();
return;
}
}
}
}
else
{
for (int y = 0; y < slots.Count; y++)
{
if (slots[y].childCount <= 0)
{
if (isFull[y] == false)
{
Instantiate(item, slots[y]);
slots[y].GetChild(0).GetComponent<InventoryItem>().amount = amount;
CheckSlots();
return;
}
}
}
}
}
}
}
When the SlottedItemID does not match the PickupItemID, it runs this
else
{
for (int y = 0; y < slots.Count; y++)
{
if (slots[y].childCount <= 0)
{
if (isFull[y] == false)
{
Instantiate(item, slots[y]);
slots[y].GetChild(0).GetComponent<InventoryItem>().amount = amount;
CheckSlots();
return;
}
}
}
}
My code adds a new stack/item to the inventory when this code runs and it does, but when the function runs into an item that is not of the same type, it only runs this bit of code until the inventory is full.
Is there a way to skip an iteration or make it so ForLoop of i will run the top of my code starting from the slot after the loop runs into the item ID that does not match?