要实现在Scene窗口下显示拖拽Prefab的样子,可以使用Unity的预制体(Prefab)概念和Unity编辑器窗口(UnityEditorWindow)功能。

首先,创建一个新的Unity编辑器窗口类,这个窗口将用于我们的拖拽Prefab功能。在类中添加以下代码:

using UnityEngine;
using UnityEditor;

public class DragAndDropPrefabWindow : EditorWindow
{
    GameObject prefab;

    [MenuItem("Window/Drag and Drop Prefab")]
    public static void ShowWindow()
    {
        GetWindow<DragAndDropPrefabWindow>("Drag and Drop Prefab");
    }

    void OnGUI()
    {
        GUILayout.Label("Drag and Drop a Prefab Here", EditorStyles.boldLabel);

        var e = Event.current;
        var dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
        GUI.Box(dropArea, "Drop a Prefab Here");

        switch (e.type)
        {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (!dropArea.Contains(e.mousePosition))
                {
                    break;
                }

                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                if (e.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();

                    foreach (var draggedObject in DragAndDrop.objectReferences)
                    {
                        var draggedPrefab = draggedObject as GameObject;
                        if (draggedPrefab == null)
                        {
                            continue;
                        }

                        prefab = draggedPrefab;
                    }
                }
                break;
        }

        if (prefab != null)
        {
            GUILayout.Label("Prefab:", EditorStyles.boldLabel);
            GUILayout.Label(prefab.name, EditorStyles.label);
            GUILayout.Label("Drag and Drop the Prefab into the Scene to Instantiate", EditorStyles.boldLabel);
        }
    }
}

这个窗口类包含一个GameObject变量,用于存储拖拽的Prefab。还有一个OnGUI方法,用于在窗口中显示GUI元素。

接下来,我们将在OnGUI方法中添加一个可拖拽区域,用户可以将Prefab拖放到该区域中。当用户将一个Prefab拖放到该区域时,我们将在可视化模式下将物体放置在该区域中。

最后,我们将在窗口中显示拖拽的Prefab的名称,并提供一个提示,让用户将其拖放到场景中进行实例化。

现在,我们可以使用以下代码在Unity Editor中打开这个窗口:

[MenuItem("Window/Drag and Drop Prefab")]
public static void ShowWindow()
{
    GetWindow<DragAndDropPrefabWindow>("Drag and Drop Prefab");
}

当我们将Prefab拖放到窗口中的可拖拽区域中时,我们将在窗口中显示Prefab的名称。然后,我们可以将它拖放到Scene窗口中进行实例化。

UnityEditorWindow实现拖拽Prefab时在Scene窗口下显示Prefab样子

原文地址: http://www.cveoy.top/t/topic/zvK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录