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);
        }
    }
}
相关推荐
郝学胜-神的一滴5 小时前
Horse3D引擎研发笔记(四):在QtOpenGL下仿three.js,封装EBO绘制四边形
c++·3d·unity·游戏引擎·godot·图形渲染·虚幻
研究是为了理解7 小时前
Linux Shell:Nano 编辑器备忘
linux·运维·编辑器
还债大湿兄8 小时前
深入解析游戏引擎(OGRE引擎)通用属性系统:基于Any类的类型安全动态属性设计
安全·游戏引擎·ogre·任意类型
郝学胜-神的一滴8 小时前
游戏引擎(Unreal Engine、Unity、Godot等)大对比:选择最适合你的工具
程序人生·unity·游戏引擎·godot·虚幻·unreal engine
玩代码11 小时前
Unity插件DOTween使用
unity·游戏引擎
伽蓝_游戏13 小时前
UGUI源码剖析(5):事件的旅程——EventSystem的架构与输入处理管线
游戏·ui·unity·架构·c#·游戏引擎·.net
与火星的孩子对话14 小时前
Unity大型场景性能优化全攻略:PC与安卓端深度实践 - 场景管理、渲染优化、资源调度 C#
android·unity·性能优化·c#
下水道的臭老鼠1 天前
vscode+latex本地英文期刊环境配置
ide·vscode·编辑器
SmalBox1 天前
【渲染流水线】[应用阶段]-[渲染命令队列]以UnityURP为例
unity·渲染