Why is drag and drop not working?
I am making a drag and drop inventory system, and so far, it's going pretty well. But I have ran into a crazy and annoying issue. When an item is picked up, it is displayed in the inventory. The item can be dragged to the 2nd, 3rd, or 4th slot of the 4 slot inventory, but if I try to drag it back to the 1st inventory slot, it does not work. Here is the code: [code]void IEndDragHandler.OnEndDrag(PointerEventData eventData) { if(DisplayItem == null) return;
//Set Slot back to original position
IconImage.rectTransform.position = originalPos;
IconImage.transform.parent.SetSiblingIndex(previousIndex);
Transform parent = IconImage.transform.parent.parent;
Slot[] slots = new Slot[parent.childCount];
for(int i = 0; i < slots.Length; i++) {
Transform slotTransform = parent.GetChild(i);
Slot slot = slotTransform.GetComponent<Slot>();
float width = slot.IconImage.rectTransform.rect.width;
float height = slot.IconImage.rectTransform.rect.height;
Vector2 slotPos = slot.transform.position;
float distance = Vector2.Distance(eventData.position, slotPos);
print("NAME:" + slot.name + " - " + distance);
if(distance < 100.0f) {
transform.SetSiblingIndex(i);
IconImage.rectTransform.position = slot.IconImage.rectTransform.position;
}
}
}[/code] I know the problem is that when the Item isn't in the 1st slot, on the line where I am printing out the distance, the same exact distance is printed twice, yet with different game object names. So please help me figure out why I can't drag back to the first slot!
Thanks, Kyle
EDIT: I have just found out that if there is 2 items in the inventory, then items can only be dragged to the 3rd and 4th slots, and not the 1st and 2nd slots. And if there are 3 items then only slot 4... So on and so on. I really have no idea what is happening anymore. If more code is needed, please, let me know!
Answer by KyleStank · Sep 10, 2016 at 05:06 PM
Omfg I got. Such a facepalm moment. On line 26, I put IconImage.rectTransform.position= slot.IconImage.rectTransform.position;
This should be IconImage.rectTransform.position = slot.transform.position; I could also use the slotPos variables instead. This is because the current slot's original position of it's icon may have changed, so using it's icon position is not what we want. Omg, I can't believe I made this mistake and didn't catch it for 3 days LOL.
Your answer
Follow this Question
Related Questions
Display list as UI or GUI 0 Answers
Inventory Script 0 Answers
switch between 5 Ui icons by pressing a button 0 Answers
Canvas Inventory closing 0 Answers
How to make an Inventory Hotbar (C#) 0 Answers