Differentiate Between Click/Drag on an Image

I looked at the demo Drag and Drop example and it’s actually something very close to what I was implementing in my project, but I’m running into a problem: OnBeginDrag seems to completely trump OnPointerClick.

Basically, I like the drag-and-drop functionality, but if a player just clicks the image then something else happens and I can’t figure out how to do this.

Hi
Just add IPointerClickHandler interface to demo DragMe script
and move icon creation from OnBeginDrag to OnDrag event like so:

public void OnDrag(PointerEventData data)
    {
        if (m_DraggingIcon == null)
        {
            var canvas = FindInParents<Canvas>(gameObject);
            if (canvas == null)
                return;

            // We have clicked something that can be dragged.
            // What we want to do is create an icon for this.
            m_DraggingIcon = new GameObject("icon");

            m_DraggingIcon.transform.SetParent(canvas.transform, false);
            m_DraggingIcon.transform.SetAsLastSibling();

            var image = m_DraggingIcon.AddComponent<Image>();
            // The icon will be under the cursor.
            // We want it to be ignored by the event system.
            m_DraggingIcon.AddComponent<IgnoreRaycast>();

            image.sprite = GetComponent<Image>().sprite;
            image.SetNativeSize();

            if (dragOnSurfaces)
                m_DraggingPlane = transform as RectTransform;
            else
                m_DraggingPlane = canvas.transform as RectTransform;
        }
          
        SetDraggedPosition(data);
    }

oh, and you can remove IBeginDragHandler because it’s not suppose to do anything now

1 Like

So, that’s kind of what I was thinking, but the OnPointerClick event never gets triggered still.

Well, I got it working; I just also had to add/handle IPointerDownHandler. Which is strange. But it works. So mini-win!

That’s weird it does works for me… Have you added IPointerClickHandler to DragMe class declaration?

public class DragMeClickMe : MonoBehaviour, ..., IPointerClickHandler
{
    ...
    public void OnPointerClick(PointerEventData eventData) 
    {
        Debug.Log("clicked me"); 
    }
}

Yeah, this is my current class definition that works (removing IPointerDownHandler will stop it from detecting clicks):

public class PDUI_DragObject : MonoBehaviour, IPointerDownHandler, IPointerClickHandler, IDragHandler, IEndDragHandler