I’m working on a system for combining items in a player’s inventory. I’ve got an array of GameObjects which represents the inventory. When an item is dropped into a slot in the inventory, the game should automatically check it and combine with adjacent items. (For example, if I drop a Plank in Slot 2 and there are Nails in Slot 1, then the game should automatically create Plank-with-Nails, and destroy the Plank and Nails.) Item combinations can require up to 3 items, and some of those are built out of 2-item combos (for example, Plank + Nails + Poison could be made with Plank-with-Nails and Poison, or with Plank, Nails, and Poison). Each row in the inventory can only contain up to 3 items.
My current logic is pretty ugly, with 2 nested For loops and 4 nested if statements. I’d like to make it better, to avoid the ire of Future Me.
Here’s the simplified version of what I’m currently doing:
// When an item is placed, check it against an array containing all of the possible combo items.
foreach(ItemCombo itemCombo in comboList.threeItemCombos)
{
if ((itemCombo.baseItem + "").Equals(itemType) || (itemCombo.secondItem+ "").Equals(itemType) || (itemCombo.hasThirdItem itemCombo.thirdItem+ "").Equals(itemType))
{
GameObject baseItem= null;
GameObject secondItem = null;
GameObject thirdItem = null;
for (int i = 0; i < 3; i++)
if (inventory[itemRow[i]]) // If there is an item in that spot
if (inventory[itemRow[i]].GetComponent<ComboItem>())
{
// If the combo item has three components, return because it's a final item.
// Else if it's a combo item, make sure that all of the components for the combo item are components for the new item.
}
else
{
// If the item is the first item for the combo, then baseItem = inventory[itemRow[i]];
// Else if the item is the first item for the combo, then secondItem = inventory[itemRow[i]];
// Else if the item is the first item for the combo, then thirdItem = inventory[itemRow[i]];
}
if (baseItem secondItem (thirdItem || !itemCombo.hasThirdItem))
{
// Create combo item
// Destroy all components
}
}
}
I really need a solution for this, and despite thinking about it for about a day I haven’t been able to think of a good solution. I’m hesitant to code possible combinations into the components themselves, because I want the list of combinations to be easy to expand and change.