EDIT: SOLVED!
Hi, first time posting. Apologies if this is redundant thread or incorrectly placed.
My InventoryObject code currently works, up to a point. Player can drag and drop item into inventory slot. If item is not dropped into inventory slot, item returns to original position within scene.
However, if I quickly click and release the item while it is still in the scene, a duplicate item is created. Attached is a picture where I clicked on the item several times, creating a new item each time. Since this happens when I release the mouse, I think the problem must be during the OnEndDrag() method, but I can’t find anything wrong with it. Here is the method:
public void OnEndDrag(PointerEventData pointerEventData)
{
if (ItemIsInsideInventory == false)
{
//if not dropped into inventory, dragged object should return to original position in scene
if (transform.parent == dragCanvas.transform)
{
transform.position = instantiatedPos;
transform.SetParent(sceneCanvas.transform);
transform.localScale = originalLocalScale;
GetComponent<Image>().raycastTarget = true;
}
else //if successfully dropped into inventory:
{
parentToReturnTo = this.transform.parent.transform; //parentToReturnTo is the parent transform
transform.position = parentToReturnTo.position;
transform.localScale = originalLocalScale;
GetComponent<Image>().raycastTarget = true;
ItemIsInsideInventory = true;
}
}
else //if (ItemIsInsideInventory == true)
{
if (transform.parent == dragCanvas.transform)
{
transform.SetParent(parentToReturnTo); //previously set as inventory slot transform during OnDrop
transform.position = parentToReturnTo.position;
transform.localScale = originalLocalScale;
GetComponent<Image>().raycastTarget = true;
}
else // item successfully dropped into different inventory slot
{
parentToReturnTo = this.transform.parent.transform;
this.transform.position = parentToReturnTo.position;
transform.localScale = originalLocalScale;
GetComponent<Image>().raycastTarget = true;
}
}
}
If item is in an inventory slot, I can quickly click and release the item and it doesn’t create duplicates. The problem only appears to be when an item is hanging out in the scene.
A quick run-down of how I’m handling drag: When an item is instantiated in the scene, it is made a child of SceneCanvas. Upon OnBeginDrag, the item is made a child of DragCanvas. Upon OnEndDrag, if item’s parent is still DragCanvas (and not InventorySlot), then item is made a child of SceneCanvas again and it returns to its original position in scene.
I’m a beginner programmer, so I apologize if the code seems strangely convoluted. I would greatly appreciate any suggestions on trouble-shooting this problem or obviating the problem by changing my overall approach to handling drag.
