【问题标题】:Drop Event not firing with IDropHandler in Unity3D在 Unity3D 中未使用 IDropHandler 触发 Drop 事件
【发布时间】:2019-03-28 07:32:36
【问题描述】:

我有 2 个预制对象组成一个面板,里面有 UI.Text。一个包含拖放类,另一个包含拖放类。但是,即使拖动工作正常,也永远不会执行 OnDrop() 函数。我还在添加到主 Canvas 的 CanvasGroup 中将 blockRaycasts 设置为 false。

 GetComponentInParent<CanvasGroup>().blocksRaycasts = false;

当我将对象拖入其中时,从 UnityEngine.EventSystems.IDropHandler 接口实现的方法 OnDrop() 是否有任何原因可能不会触发?

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

【问题讨论】:

    标签: c# unity3d drag-and-drop


    【解决方案1】:

    问题可能是由于您将 CanvasGroup 添加到 MainCanvas 然后将 blocksRaycast 设置为 false 以获取完整的 MainCanvas 本身。所以基本上你所有的输入都通过你的画布没有任何影响。

    问题的解决方案:

    1. 删除主画布的画布组
    2. 将 Canvas-Group-Component 添加到要拖动的 Prefab 或 GameObject
    3. 然后您可以使用 CanvasGroup 的 GetComponent 来更改 OnBeginDrag(...) 中的 blocksRaycast-property
    4. 不要忘记在 OnEndDrag(...) 中将 blocksRaycast-property 设置为 true 以使其再次可拖动

    这里是 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");
        }
    }
    

    【讨论】:

    • 谢谢,非常感谢,这正是问题所在。事实上,我并不真正了解光线投射的工作原理或它们为何存在,所以这可能是我的问题的原因。
    • 简短回答:光线投射是在您的场景中发射一条光线并观察是否有任何交叉点/命中。最“困难”的部分是从不同空间转换回世界空间,因此光线会撞击世界空间中的对象。
    猜你喜欢
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多