Unity编辑器-获取Projectwindow中拖拽内容的路径

参考

Unity Editor 实现给属性面板上拖拽赋值资源路径

API

Event
DragAndDrop

示例

Mono脚本

csharp 复制代码
using UnityEngine;
public class TestScene : MonoBehaviour
{
    [SerializeField] string testName;
}

Editor脚本

重写InspectorGUI,在该函数中通过Event的Type参数获取当前的拖拽类型

拖拽中,如果鼠标指针进入目标区域,修改鼠标指针

拖拽释放,判断鼠标是否在目标区域,如果是,获取拖拽内容的路径
注意:不设置鼠标指针为通用状态无法获取拖拽对象的路径

csharp 复制代码
using UnityEditor;
[CustomEditor(typeof(TestScene))]
public class TestSceneInspector : Editor
{
    SerializedProperty testName;

    private void OnEnable()
    {
        testName = serializedObject.FindProperty(nameof(testName));
    }

    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        EditorGUILayout.PropertyField(testName, new GUIContent("测试"));

        if (GetDragObjectPathsInProjectWindow(GUILayoutUtility.GetLastRect(), out string[] paths))
        {
            if (paths.Length > 0)
                testName.stringValue = System.IO.Path.GetFileNameWithoutExtension(paths[0]);
        }
        serializedObject.ApplyModifiedProperties();
    }

    bool GetDragObjectPathsInProjectWindow(Rect targetRect, out string[] paths)
    {
        //拖拽提示
        if (Event.current.type == EventType.DragUpdated)
        {
            Event.current.Use();
            if (DragObjectInArea(targetRect))
                DragAndDrop.visualMode = DragAndDropVisualMode.Generic;//鼠标指针修改为通用拖拽模式,设置为该模式该可以获取拖拽对象的路径
            else
                DragAndDrop.visualMode = DragAndDropVisualMode.None;//鼠标指针修改为无指示模式         
        }

        //拖拽释放并且在目标区域内
        if (Event.current.type == EventType.DragPerform && DragObjectInArea(targetRect))
        {
            Event.current.Use();
            paths = DragAndDrop.paths;
            return true;
        }
        else
        {
            paths = null;
            return false;
        }

        bool DragObjectInArea(Rect rect)
        {
            return rect.Contains(Event.current.mousePosition);
        }
    }
}
相关推荐
BF062415 小时前
EPICS ARCHIVER APPLIANCE
编辑器·epics
世洋Blog15 小时前
数据驱动与MVC
unity·mvc
黑科技编辑器15 小时前
SVG编辑器如何生成浪漫全屏下雪特效图文?
编辑器·新媒体运营·交互·微信公众平台
WMX101215 小时前
Unity添加近身菜单-MRTK
unity·游戏引擎
Jeking21716 小时前
初探新一代workflow编辑器unione flow editor:企业级流程设计的高效解决方案
编辑器·流程图·workflow·工作流·flow editor·unione cloud
我命由我123451 天前
VSCode - Prettier 配置格式化的单行长度
开发语言·前端·ide·vscode·前端框架·编辑器·学习方法
在路上看风景1 天前
15. 纹理尺寸是4的倍数
unity
星依网络1 天前
使用LabelImg工具标注数据(游戏辅助脚本开发)
python·游戏引擎·图形渲染·骨骼绑定
AT~1 天前
unity 使用Socket和protobuf实现网络连接
unity·游戏引擎
有梦想的鱼1 天前
vscode letax编译中英文论文(傻瓜式、一分钟)
ide·vscode·编辑器