3

I have 2 prefabs objects consisting in a panel with UI.Text inside. One contains the class for dragging and the other the dropping. However, even if the drag works fine the OnDrop() function is never executed. I have also set the blockRaycasts to false in the CanvasGroup that I added to the main Canvas.

 GetComponentInParent<CanvasGroup>().blocksRaycasts = false;

Are there any reasons why the method OnDrop() implemented from the interface UnityEngine.EventSystems.IDropHandler may not be firing while I'm dragging an object into it?

public class ItemDropHandler : MonoBehaviour, IDropHandler
{
    public void OnDrop(PointerEventData eventData)
    {
        Debug.Log("Drop detected over the UI.Text"); //this is never shown
    }
}

1 Answer 1

5

The problem is maybe caused by the fact, that you add the CanvasGroup to the MainCanvas and then set blocksRaycast to false for the complete MainCanvas itself. So basically all your inputs are going through your canvas without any effect.

The solution for the problem:

  1. Remove the canvas Group of your main canvas
  2. Add the Canvas-Group-Component to the Prefab or GameObject you want to drag
  3. Then you can use GetComponent for the CanvasGroup to change the blocksRaycast-property in OnBeginDrag(...)
  4. Don't forget to set the blocksRaycast-property to true in OnEndDrag(...) to make it draggable again

Here is some example code for the DragHandler:

public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("OnBeginDrag");
        GetComponent<CanvasGroup>().blocksRaycasts = false;
    }

    public void OnDrag(PointerEventData eventData)
    {
        gameObject.transform.position = Input.mousePosition;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        GetComponent<CanvasGroup>().blocksRaycasts = true;
        Debug.Log("OnEndDrag");
    }
}
2
  • Thank you, thank you soooo much, that was exactly the issue. The truth is that I don't really understand how raycasts works or why they are there, so that's the probable cause of my problem. Commented Mar 28, 2019 at 1:09
  • Short answer: Raycasting is to shot a ray through your scene and observe if there are any intersections/hits. The most "difficult" part is the transformation from the different spaces back to the world space so the ray hits the object in the world space.
    – MSauer
    Commented Mar 28, 2019 at 7:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.