【Unity Editor】拽托资源到Inspector面板实现将资源路径赋值给属性

我的需求是这样的,从资产面板中拖拽一个文件,到某个属性面板框中,然后获取这个文件的路径,赋值给对应的路径变量。

这里感谢魔术师Dix的博文【Unity Editor】实现给属性面板上拖拽赋值资源路径。

根据博文的思路

(1)绘制一个Rect;

(2)鼠标在拖拽中,那么判定是否拖到这个文本框里面了;

(3)拖进来的时候有选中文件,那么就调用API获取路径;

(4)进行赋值操作。

实现了拖拽赋值的功能,具体实现如下:

1.基于的MonoBehaviour的属性脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class MyData : MonoBehaviour
{
   [SerializeField]
   public string m_myPath;

    public string GetPdfPath()
    {
        return m_myPath;
    }
    public void SetPdfPath(string path)
    {
         m_myPath= path;
    }
}

2.重载Editor的脚本BaseDataEditor 实现  

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(MyData),true)]
[CanEditMultipleObjects]
public class BaseDataEditor : Editor
{
    //序列化对象
    private SerializedObject obj;
    MyData m_OrginData;
    //学历恶化属性
    private SerializedProperty MyPath;

    Rect mPathRect;

    private void OnEnable()
    {
        obj = new SerializedObject(target);

        MyPath = obj.FindProperty("m_myPath");

        m_OrginData= (MyData)target;
    }

    public override void OnInspectorGUI()
    {
       

        EditorGUILayout.PropertyField(MyPath);

        //获得一个长500的框  
        mPathRect = EditorGUILayout.GetControlRect(GUILayout.Width(500));
        //如果鼠标正在拖拽中或拖拽结束时,并且鼠标所在位置在文本输入框内  
        if (( Event.current.type == EventType.DragUpdated|| Event.current.type == EventType.DragExited) && mExcelPathRect.Contains(Event.current.mousePosition))
        {
            //改变鼠标的外表  
            DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
            if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0)
            {
                string retPath = DragAndDrop.paths[0];
                MyPath.stringValue = retPath;
                m_OrginData.SetPdfPath(retPath);
            }

            obj.ApplyModifiedProperties();
            obj.Update();

        }

    
    }
}

 

你可能感兴趣的:(unity)