更新了一下,支持数组和嵌套数据结构。

 using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Reflection; [CustomPropertyDrawer(typeof(ObjectToPathAttribute))]
public class ObjectToPathDrawer : PropertyDrawer
{ public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
Object target = property.serializedObject.targetObject;
ObjectToPathAttribute otpa = attribute as ObjectToPathAttribute;
System.Type objType = otpa._objType; string path = property.stringValue;
position.width = EditorGUIUtility.labelWidth * 2.0f / 3.0f; EditorGUI.LabelField(position, label);
position.x += EditorGUIUtility.labelWidth * 2.0f / 3.0f; Object _obj = null;
bool _foundObj = true;
if (!string.IsNullOrEmpty(path))
{
_obj = AssetDatabase.LoadMainAssetAtPath(path);
if (_obj == null)
{
_foundObj = false;
}
}
_obj = EditorGUI.ObjectField(position, _obj, objType, false);
if (_obj != null)
{
path = AssetDatabase.GetAssetPath(_obj);
}
else
{
if (_foundObj)
{
path = string.Empty;
}
}
position.x += EditorGUIUtility.labelWidth * 2.0f / 3.0f;
position.width = EditorGUIUtility.labelWidth;
property.stringValue = EditorGUI.TextField(position, path);
}
}

ObjectToPathDrawer

 using UnityEngine;
using System.Collections; public class ObjectToPathAttribute : PropertyAttribute
{
public System.Type _objType;
public ObjectToPathAttribute(System.Type t)
{
_objType = t;
}
}

ObjectToPathAttribute

 using UnityEngine;
using System.Collections; public class TestClass : MonoBehaviour
{
[ObjectToPath(typeof(GameObject))]
public string _prefabPath;
}

TestClass

使用上面的代码可以通过拖拽一个prefab的方式把相应的路径直接存储到public string _itemPerfabPath里,省去键盘输入步骤。不支持场景中的GameObject的拖入。

截图如下:

通过拖拽prefab来存储相应的路径-LMLPHP

当prefab为空的时候的截图如下:

通过拖拽prefab来存储相应的路径-LMLPHP

05-12 11:35