Question by
prefix · Jan 23, 2017 at 02:42 AM ·
uidrag-and-dropevent-handling
Drag and Drop
Below is a snapshot of whats happening and what im trying to accomplish. When i drag an item to the appropriate slot, it stays. However when I drag a different item on top of the one that's already there, I want it to go back to its original (sub)parent/start position. What's happening is that all objects are going to the same (sub) parent.
Im not sure where im going wrong in code. (beginner programmer)
So the question is, how do i get the "already" dragged item, to return to its original parent when i drag another item on top of it?
Thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
/// <summary>
/// THIS HANDLES THE SELECTING AND DRAGGING OF THE OBJECT
/// </summary>
public static GameObject itemBeingDragged;
Vector3 startPosition;
Transform startParent;
public static Transform originalStartParent;
#region IBeginDragHandler implementation
void Start()
{
originalStartParent = gameObject.transform.parent;
}
public void OnBeginDrag (PointerEventData eventData)
{
itemBeingDragged = gameObject;
startPosition = transform.position;
startParent = transform.parent;
GetComponent<CanvasGroup> ().blocksRaycasts = false;
}
#endregion
#region IDragHandler implementation
public void OnDrag (PointerEventData eventData)
{
transform.position = Input.mousePosition;
}
#endregion
#region IEndDragHandler implementation
public void OnEndDrag (PointerEventData eventData)
{
itemBeingDragged = null;
GetComponent<CanvasGroup> ().blocksRaycasts = true;
if (transform.parent == startParent)
{
transform.position = startPosition;
}
}
#endregion
}
//------------------------------------------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Slot : MonoBehaviour, IDropHandler {
/// <summary>
// THIS HANDLES WHICH SLOTS CAN GRAB THE ITEM
///
public GameObject item
{
get
{
if (transform.childCount > 0)
{
return transform.GetChild (0).gameObject;
}
return null;
}
}
#region IDropHandler implementation
public void OnDrop (PointerEventData eventData)
{
if (!item)
DragHandler.itemBeingDragged.transform.SetParent (transform);
else if (item)
item.transform.SetParent (DragHandler.originalStartParent);
DragHandler.itemBeingDragged.transform.SetParent (transform);
}
#endregion
}
helpfile.jpg
(123.9 kB)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612105402im_/https://answers.unity.com/themes/thub/images/avi.jpg)