IDragHandler 是否仅适用于 canvas 和 UI 项?

Does IDragHandler only works on canvas and UI items?

我关注了 example 关于使用 UnityEngine.EventSystems 拖放项目的方法,它有效。

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

public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public static GameObject itemBeingDragged;
    private Vector3 startPosition;
    private Transform startParent;

    public void OnBeginDrag(PointerEventData eventData)
    {
        itemBeingDragged = gameObject;
        startPosition = transform.position;
        startParent = transform.parent;
        GetComponent<CanvasGroup>().blocksRaycasts = false;
    }

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

    public void OnEndDrag(PointerEventData eventData)
    {
        itemBeingDragged = null;
        GetComponent<CanvasGroup>().blocksRaycasts = true;
        if (transform.parent == startParent)
            transform.position = startPosition;
    }
}

但是如果我将脚本组件添加到 canvas 中的精灵,则相同的代码将不起作用。所以我必须使用这段代码来拖放精灵。

using UnityEngine;
using System.Collections;

public class DragDrop : MonoBehaviour {

    private Vector3 offset;

    void OnMouseDown()
    {

        offset = gameObject.transform.position -
            Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 4f));
    }

    void OnMouseDrag()
    {
        Vector3 newPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 4f);
        transform.position = Camera.main.ScreenToWorldPoint(newPosition) + offset;
    }
}

但是这样我无法检测到一个游戏对象是否已经被丢弃到另一个游戏对象,这可以通过canvas中的IDropHandler.OnDrop来完成。

那么在 Unity 中,我是否必须仅在 canvas 和 UI 项上使用 IDragHandler 和 EventSystem?

是否有任何替代方法可以在不使用 canvas 的情况下检测游戏对象中掉落的物品?

IDragHandler -> interfaceUnityEngine.EventSystems 实现所有 EventSystem 事件继承自的 interfaces: IEventSystemHandler -> base class。

Class in UnityEngine.EventSystems 继承自:EventSystems.UIBehaviour

所以… IDragHandlerEventSystem 仅在 上工作 canvas 和 UI 项。