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);
        }
    }
}
相关推荐
qq_205279055 小时前
Unity TileMap 使用经验
unity·游戏引擎
心灵宝贝7 小时前
Mac Unity 2018.dmg游戏工具 安装步骤 简单易懂教程(附安装包)
macos·unity·游戏引擎
TO_ZRG8 小时前
Unity SDK 通过 Registry 分发及第三方依赖处理指南
unity·游戏引擎
7***n7513 小时前
C++在游戏中的Cocos2d-x
游戏·游戏引擎·cocos2d
dntktop15 小时前
搜索+计算+插件…这个“全能管家”让你告别80%的桌面图标
运维·windows·自动化·编辑器
龙智DevSecOps解决方案19 小时前
Perforce《2025游戏技术现状报告》Part 1:游戏引擎技术的广泛影响以及生成式AI的成熟之路
人工智能·unity·游戏引擎·游戏开发·perforce
Y***K4341 天前
C在游戏中的Godot
游戏·游戏引擎·godot
西风未眠1 天前
高效编辑之vi/vim常用快捷键汇总
linux·编辑器·vim
温轻舟1 天前
Python自动办公工具01-Excel文件编辑器
开发语言·python·编辑器·excel·温轻舟
WarPigs2 天前
Unity编辑器开发笔记
unity·编辑器·excel