更新了一下,支持数组和嵌套数据结构。
1 using UnityEngine; 2 using System.Collections; 3 using UnityEditor; 4 using System.Reflection; 5 6 [CustomPropertyDrawer(typeof(ObjectToPathAttribute))] 7 public class ObjectToPathDrawer : PropertyDrawer 8 { 9 10 public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)11 {12 Object target = property.serializedObject.targetObject;13 ObjectToPathAttribute otpa = attribute as ObjectToPathAttribute;14 System.Type objType = otpa._objType;15 16 string path = property.stringValue;17 position.width = EditorGUIUtility.labelWidth * 2.0f / 3.0f;18 19 EditorGUI.LabelField(position, label);20 position.x += EditorGUIUtility.labelWidth * 2.0f / 3.0f;21 22 Object _obj = null;23 bool _foundObj = true;24 if (!string.IsNullOrEmpty(path))25 {26 _obj = AssetDatabase.LoadMainAssetAtPath(path);27 if (_obj == null)28 {29 _foundObj = false;30 }31 }32 _obj = EditorGUI.ObjectField(position, _obj, objType, false);33 if (_obj != null)34 {35 path = AssetDatabase.GetAssetPath(_obj);36 }37 else38 {39 if (_foundObj)40 {41 path = string.Empty;42 }43 }44 position.x += EditorGUIUtility.labelWidth * 2.0f / 3.0f;45 position.width = EditorGUIUtility.labelWidth;46 property.stringValue = EditorGUI.TextField(position, path);47 }48 }
1 using UnityEngine; 2 using System.Collections; 3 4 public class ObjectToPathAttribute : PropertyAttribute 5 { 6 public System.Type _objType; 7 public ObjectToPathAttribute(System.Type t) 8 { 9 _objType = t;10 }11 }
1 using UnityEngine;2 using System.Collections;3 4 public class TestClass : MonoBehaviour5 {6 [ObjectToPath(typeof(GameObject))]7 public string _prefabPath;8 }
使用上面的代码可以通过拖拽一个prefab的方式把相应的路径直接存储到public string _itemPerfabPath里,省去键盘输入步骤。不支持场景中的GameObject的拖入。
截图如下:
当prefab为空的时候的截图如下: