- Home /
Question by
SheldonM07 · Apr 01, 2019 at 05:46 AM ·
inventory system
When I drag and drop an item I just picked up into the same slot, it disappears. How do I fix this?
public class SlotUi : MonoBehaviour, IDropHandler { protected GameObject icon; protected int slotIndex; private Text stack;
protected ItemHolder.ItemSlot thisItemSlot;
protected ItemHolder.ItemSlot droppedItemSlot;
protected virtual void Start() {
slotIndex = transform.GetSiblingIndex();
icon = transform.GetChild(0).gameObject;
stack = icon.transform.GetChild(0).GetComponent<Text>();
}
public virtual void OnDrop(PointerEventData eventData)
{
droppedItemSlot = eventData.pointerDrag.GetComponent<ItemDragHandler>().GetItemSlot();
}
protected void HandleItemDrop(PointerEventData eventData) {
if (thisItemSlot.item != null)
{
if (thisItemSlot.item == droppedItemSlot.item)
{
if (thisItemSlot.currentStack < thisItemSlot.item.maxStack)
{
if (droppedItemSlot.currentStack <= thisItemSlot.item.maxStack - thisItemSlot.currentStack)
{
thisItemSlot.currentStack += droppedItemSlot.currentStack;
droppedItemSlot.Clear();
}
else
{
int stackDifference = thisItemSlot.item.maxStack - thisItemSlot.currentStack;
thisItemSlot.currentStack += stackDifference;
droppedItemSlot.currentStack -= stackDifference;
}
}
}
else
{
SwapItems(eventData);
}
}
else {
DropOntoEmptySlot();
}
InventoryHandler.instance.UpdateInventoryUI();
}
private void DropOntoEmptySlot() {
thisItemSlot.item = droppedItemSlot.item;
thisItemSlot.currentStack = droppedItemSlot.currentStack;
droppedItemSlot.Clear();
}
protected virtual void SwapItems(PointerEventData eventData) {
ItemHolder.ItemSlot tempSlot = new ItemHolder.ItemSlot(thisItemSlot.item, thisItemSlot.currentStack);
thisItemSlot.item = droppedItemSlot.item;
thisItemSlot.currentStack = droppedItemSlot.currentStack;
droppedItemSlot.item = tempSlot.item;
droppedItemSlot.currentStack = tempSlot.currentStack;
}
public void RefreshItemIcons() {
if (thisItemSlot.item != null)
{
icon.GetComponent<Image>().sprite = thisItemSlot.item.icon;
if (thisItemSlot.currentStack > 1)
{
stack.text = "x" + thisItemSlot.currentStack;
}
else
{
stack.text = "";
}
icon.SetActive(true);
}
else
{
icon.SetActive(false);
}
}
}
Comment
You need to check if the object you're dropping is the same as the object you're dropping into, if so, then just snap it back into place and return out of the code, no reason to alter or change the slot if it will remain the same.
Your answer
Follow this Question
Related Questions
Not all code paths return a value? 1 Answer
C# Lists & Inventory Logic 0 Answers
How do I make my item only open if there is room in my Inventory? 3 Answers
Suggestions on the best way to handle an inventory system? [Adding, removing, best practice] 0 Answers
Using a game object as a UI image for inventory slots 1 Answer