- Home /
OnDrag only called once?
I'm making a simple drag and drop. The player supposes to drag an object from inventory to another item slot. When dragged(OnBeginDrag), the object will be the direct child of the canvas, so it will appear in front all the other UI stuff. When dropped (OnEndDrag) near/directly above the item slot, it will snap into the slot and become the child of the slot. If it's dropped too far from the item slot, it will return back to the inventory.
Problem is that it will only allow me to drag once if the object snaps to the item slots. That means once SetParent(go.transform) and anchoredPosition is called, I can't drag the object anymore.
Help! GameObject originalSlot; public GameObject[] slotsForCalculation;
public void OnBeginDrag (PointerEventData eventData)
{
originalSlot = transform.parent.gameObject;
//makes the object infront all the other UI
transform.SetParent (GameObject.Find ("Canvas").transform, true);
}
public void OnDrag(PointerEventData eventData)
{
//moves object with mouse position
transform.position = new Vector3 (eventData.position.x, eventData.position.y, transform.position.z);
}
public void OnEndDrag (PointerEventData eventData)
{
bool wentToNewSlot = false;
foreach (GameObject go in slotsForCalculation) {
//if object is not too far from the new slot...
if (transform.position.x < (go.transform.position.x + 50f) && transform.position.x > (go.transform.position.x - 50f) && transform.position.y < (go.transform.position.y + 50f) && transform.position.y > (go.transform.position.y - 50f) ) {
//set object parent as new slot
transform.SetParent (go.transform);
//make sure the object is aligned with the new slot
GetComponent<RectTransform> ().anchoredPosition = new Vector2 (0, 0);
wentToNewSlot = true;
}
}
//if object is too far from the new slot...
if (!wentToNewSlot) {
//set object parent as original slot
transform.SetParent (originalSlot.transform);
//make sure the object is aligned with the original slot
GetComponent<RectTransform> ().anchoredPosition = new Vector2 (0, 0);
}
wentToNewSlot = false;
}
Answer by elwhywhy · Jan 16, 2017 at 02:56 PM
HAHA STUPID ME I had a gameobject above, blocking the dragging item, so Unity thinks that Im trying to drag the above gameobject. After I place the dragging item above the the blocking gameobject, it worked!