Hello all,
The inventory system I’m working on has a drag-and-drop functionality, which includes the ability to drag an item onto another, swapping their positions. Unfortunately what I have ended up with is a mess of if statements that I know can be simplified. I’ve tried a couple of different options including using enums to define states and even writing a state machine. Both of these have failed to simplify the code.
It works fine, but it is screaming to be refactored.
Any ideas?
public void OnEndDrag(PointerEventData eventData)
{
InventoryItem currentInventoryItem = _inventory.FindInventoryItemFromUIElement(this);
if (currentInventoryItem != null)
{
GameObject objectLandedOn = eventData.pointerEnter;
InventoryUISlot uiSlotLandedOn = null;
InventoryItem itemLandedOn = null;
if (objectLandedOn != null)
{
uiSlotLandedOn = objectLandedOn.GetComponent<InventoryUISlot>();
itemLandedOn = _inventory.FindInventoryItemFromUIElement(uiSlotLandedOn);
}
if (uiSlotLandedOn == null)
{
_inventory.DropItem(currentInventoryItem);
}
else if (uiSlotLandedOn != null)
{
bool clearCurrentUIElement = itemLandedOn == null;
if (currentInventoryItem.item.stackSize > 1 && uiSlotLandedOn != InventoryUIManager.activeInventorySlot)
{
if (itemLandedOn != null)
{
itemLandedOn.SetNewUIElement(this, clearCurrentUIElement);
}
currentInventoryItem.SetNewUIElement(uiSlotLandedOn, clearCurrentUIElement);
}
else if (currentInventoryItem.item.stackSize == 1)
{
if (itemLandedOn == null)
{
if (uiSlotLandedOn == InventoryUIManager.activeInventorySlot)
{
_inventory.SetActiveItem(currentInventoryItem, false);
}
else if (currentInventoryItem.uiElement == InventoryUIManager.activeInventorySlot)
{
_inventory.DeleteActiveItem();
}
}
else if (itemLandedOn != null)
{
if (uiSlotLandedOn == InventoryUIManager.activeInventorySlot)
{
_inventory.SetActiveItem(currentInventoryItem, false);
}
else if (currentInventoryItem.uiElement == InventoryUIManager.activeInventorySlot)
{
_inventory.SetActiveItem(itemLandedOn, false);
}
itemLandedOn.SetNewUIElement(this, clearCurrentUIElement);
}
currentInventoryItem.SetNewUIElement(uiSlotLandedOn, clearCurrentUIElement);
}
}
ResetDragObject();
}