コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】アセットを Inspector にドラッグ&ドロップできるようにするエディタ拡張の例

ソースコード

/// <summary>
/// 指定された矩形にドラッグ & ドロップされたアセットのパスを返します
/// </summary>
public bool GetDragAndDropAssetPath( Rect rect, out string assetPath )
{
    var current   = Event.current;
    var controlId = GUIUtility.GetControlID( FocusType.Passive );

    assetPath = string.Empty;

    switch ( current.type )
    {
        case EventType.DragUpdated:
        case EventType.DragPerform:

            if ( !rect.Contains( current.mousePosition ) ) break;

            DragAndDrop.visualMode      = DragAndDropVisualMode.Copy;
            DragAndDrop.activeControlID = controlId;

            if ( current.type == EventType.DragPerform )
            {
                DragAndDrop.AcceptDrag();

                foreach ( var draggedObject in DragAndDrop.objectReferences )
                {
                    assetPath = AssetDatabase.GetAssetPath( draggedObject );
                }

                DragAndDrop.activeControlID = 0;
            }

            current.Use();
            break;
    }

    return !string.IsNullOrWhiteSpace( assetPath );
}

使用例

if ( GetDragAndDropAssetPath( pathRect, out var assetPath ) )
{
    pathProperty.stringValue = assetPath;
}