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);
        }
    }
}
相关推荐
mxwin5 小时前
Unity Shader 半透明物体为什么不能写入深度缓冲?
unity·游戏引擎·shader
晚枫歌F6 小时前
三层时间轮的实现
网络·unity·游戏引擎
望眼欲穿的程序猿7 小时前
苹果系统使用VsCode开发QT
ide·vscode·编辑器
咸鱼永不翻身7 小时前
Lua脚本事件检查工具
unity·lua·工具
其实防守也摸鱼9 小时前
带你了解与配置phpmyadmin
笔记·安全·网络安全·pdf·编辑器·工具·调试
leo__5209 小时前
单载波中继系统资源分配算法MATLAB仿真程序
算法·matlab·unity
Rsun045519 小时前
Oracle中常用语法
编辑器
努力长头发的程序猿10 小时前
Unity使用ScriptableObject序列化资源
unity·游戏引擎
mxwin11 小时前
Unity Shader 手写基于 PBR 的 URP Lit Shader 核心光照计算
unity·游戏引擎·shader
小贺儿开发11 小时前
Unity3D 智能云端数字标牌系统
unity·阿里云·人机交互·视频·oss·广告·互动