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);
        }
    }
}
相关推荐
郝学胜-神的一滴12 分钟前
中级OpenGL教程 006:高光反射原理与 Shader 实现
c++·unity·godot·图形渲染·three.js·opengl·unreal
多云的夏天25 分钟前
IDE-VSCODE-Continue + DeepSeek V4
ide·vscode·编辑器·deepseek
Robot_Nav1 小时前
Claude Code cli 以及vscode版本的各种命令参考手册
ide·vscode·编辑器
神码编程4 小时前
【Unity】MiniGame编辑器小游戏(十六)中国象棋局域网对战【Chinese Chess】(下)
unity·编辑器·游戏引擎·小游戏
Maddie_Mo4 小时前
Unity 联动 Trae AI 项目开发基础教学
人工智能·unity·游戏引擎
新手unity自用笔记16 小时前
unity简单新手上手动画系统讲解
unity·游戏引擎
伽蓝_游戏17 小时前
第二章:深入 Unity 资源导入管线 (Asset Import Pipeline)
游戏·unity·c#·游戏引擎·游戏程序
我寄人间雪满头丶1 天前
Unity中对于数值游戏的大数显示
游戏·unity·游戏引擎
屋外雨大,惊蛰出没1 天前
Vscode自动生成类图
ide·vscode·编辑器·类图绘制
游乐码1 天前
unity基础 (三)坐标系
unity·游戏引擎