编辑器拓展-DragAndDrop

本文介绍了一个Unity编辑器窗口脚本,该脚本允许用户将场景中的物体拖放到编辑器界面,并显示物体的完整路径。通过使用DragAndDrop API和EditorWindow,实现了物体的拖放功能和路径获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

该功能演示了拖拽场景中的物体到编辑器界面。并显示物体完整路径

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class OpenWindow : EditorWindow
{
    string path;

    [MenuItem("Tools/Open")]
    static void Open()
    {
        GetWindow<OpenWindow>();
    }
    private void OnGUI()
    {
        GUILayout.BeginHorizontal();
        GUILayout.Label("Path");
        path=GUILayout.TextField(path);
        GameObject obj = GetDragGameObjectFromScene(GUILayoutUtility.GetLastRect());
        if (obj!=null)
        {
            path = GetObjectScenePath(obj);
        }
        GUILayout.EndHorizontal();
    }

    public static GameObject GetDragGameObjectFromScene(Rect r)
    {
        Event e = Event.current;
        if (e.type == EventType.DragUpdated || e.type == EventType.DragPerform)
        {
            Object dragObject = DragAndDrop.objectReferences[0];
            if (dragObject is GameObject)
            {
                if (PrefabUtility.GetCorrespondingObjectFromSource(dragObject) == null && PrefabUtility.GetPrefabInstanceHandle(dragObject) != null)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                }
                else
                {
                    if (r.Contains(e.mousePosition))
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                        if (e.type == EventType.DragPerform)
                        {
                            DragAndDrop.AcceptDrag();
                            return dragObject as GameObject;
                        }
                        e.Use();
                    }
                }
            }
            else
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
            }
        }
        return null;
    }
    public static string GetObjectScenePath(GameObject o)
    {
        string result = AssetDatabase.GetAssetPath(o);
        if (!string.IsNullOrEmpty(result))
        {
            return result;
        }

        Transform t = o.transform;
        string path = t.name;
        while (t.parent != null)
        {
            path = t.parent.name + "/" + path;
            t = t.parent;
        }
        return path;
    }
}

拖拽Sphere至Path后的框中,显示物体完整路径

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值