- Home /
Cancel a drag and drop movement
Hello!
I want to cancel a drag and drop movement programmatically. Is there a way to do this?
I am using right now the interfaces IBeginDragHandler, IDragHandler, IEndDragHandler.
What I am trying to do: I want to cancel the dragging when I leave a certain area. So when I leave the OnEndDrag Method should be called and the drag is ended.
PS: Right now I have an internal variable to see if am still dragging and stop it if I leave the area. Right now, OnEndDrag is called twice. not really ideal.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;
public class DraggableCard : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
public Text nameText;
Vector3 startPosition;
Transform startParent;
bool dragging = false;
public EventTrigger parentBox;
void Start () {
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = EventTriggerType.PointerExit;
entry.callback = new EventTrigger.TriggerEvent();
UnityEngine.Events.UnityAction<BaseEventData> callback =
new UnityEngine.Events.UnityAction<BaseEventData>(PointerExit);
entry.callback.AddListener(callback);
parentBox.delegates.Add(entry);
}
public string Info {
get { return nameText.text; }
set { nameText.text = value; }
}
public void OnBeginDrag (PointerEventData eventData)
{
dragging = true;
startPosition = transform.position;
startParent = transform.parent;
}
public void OnDrag (PointerEventData eventData)
{
if (dragging) {
Vector3 pos = transform.position;
pos.x = eventData.position.x;
transform.position = pos;
}
}
public void OnEndDrag (PointerEventData eventData)
{
if (dragging) {
StartCoroutine(SmoothMove (transform.position, startPosition,
0.2f)); dragging = false;
}
}
public void PointerExit(BaseEventData data) {
Debug.Log ("We Left!");
OnEndDrag (null);
}
}
Thanks, Matthias
Is it causing issues with OnEndDrag being called twice?
You appear to handle the issue by setting a bool so all that should be happening is it calls OnEndDrag again when you release the mouse, but that does nothing.
If so then I wouldn't be too worried about it. If not what is happening?
Answer by MilesAdamson · Dec 02, 2015 at 10:01 AM
This question is quite old but I did find the answer.
Only allow on drag to work if a flag is set
Make the flag false if you exit the zone so the drop function stops working
Make an OnPointerUp function which sets the flag again, so that you can drag again
Reset the position of the object if OnDrag is called but the flag is false
Hi,
Using flag does stop dragging, but I need need to call OnEngDrag()
How can i do that?