2
\$\begingroup\$

There is a code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class DragAndDropGame : MonoBehaviour, IBeginDragHandler, IDragHandler
{

    Camera MainCamera;

    void Awake()
    {
        MainCamera = Camera.allCameras[0];
        Debug.Log(MainCamera);
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("OnBeginDrag");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 newPos = MainCamera.ScreenToWorldPoint(eventData.position);
        newPos.z = 0;
        transform.position = newPos;
    }

    void OnMouseDown()
    {
        Debug.Log("OnMouseDown");
    }
}

OnMouseDown fulfills, but the implementation ofIBeginDragHandler, IDragHandler - not. What can be wrong?

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Do you have an EventSystem set up in the scene with a Physics2DRaycaster and a 2D Collider set up on the sprite? \$\endgroup\$
    – Ed Marty
    Commented Aug 24, 2018 at 12:04
  • \$\begingroup\$ I have sprites on 3D plane in AR. I tryed all except 2D Collider. \$\endgroup\$ Commented Aug 24, 2018 at 12:09
  • 1
    \$\begingroup\$ You'll need the EventSystem, a PhysicsRaycaster, and a collider on the sprite for those methods to work. \$\endgroup\$
    – Ed Marty
    Commented Aug 24, 2018 at 15:07

3 Answers 3

5
\$\begingroup\$

IDragHandler (and its associates) are only called for UI elements that are part of a canvas. And even then, only for UI components (Image, text, etc) and not 3D objects and colliders.

You are probably looking for OnMouseDrag.

\$\endgroup\$
1
  • \$\begingroup\$ I don't think these interfaces are limited to UI and hence canvases. This answer shows how to use these interfaces for both UI and 2D in game objects. \$\endgroup\$
    – Felix
    Commented May 24, 2020 at 23:08
1
\$\begingroup\$

You probably implemented IDragHandler, but forgot to implement IBeginDragHandler and IEndDragHandler.

All three must be implemented, otherwise OnDrag(PointerEVentData eventData) will not be called for you.

For example, this will be ok:

public class Skins_TouchingArea_UI : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler{

    public void OnDrag(PointerEventData eventData){  Debug.Log("dragging"); }

    //required for OnDrag() to work
    public void OnBeginDrag(PointerEventData eventData) {}

    //required for OnDrag() to work
    public void OnEndDrag(PointerEventData eventData) {}
}
\$\endgroup\$
-1
\$\begingroup\$

Try adding this namespace:

using UnityEngine.UI
\$\endgroup\$
1
  • \$\begingroup\$ It did not help, but elements is sprites. \$\endgroup\$ Commented Aug 24, 2018 at 6:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .