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 Object _obj = null;10 11 public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)12 {13 Object target = property.serializedObject.targetObject;14 FieldInfo fi = target.GetType().GetField(property.name);15 16 string path = string.Empty;17 EditorGUI.LabelField(position, label);18 position.x += EditorGUIUtility.labelWidth * 2.0f / 3.0f;19 if (_obj == null)20 {21 path = fi.GetValue(target).ToString();22 if (!string.IsNullOrEmpty(path))23 {24 _obj = AssetDatabase.LoadMainAssetAtPath(path);25 }26 _obj = EditorGUI.ObjectField(position, _obj, typeof(GameObject), false);27 }28 else29 {30 _obj = EditorGUI.ObjectField(position, _obj, typeof(GameObject), false);31 path = AssetDatabase.GetAssetPath(_obj);32 fi.SetValue(target, path);33 }34 35 position.x += EditorGUIUtility.labelWidth * 2.0f / 3.0f;36 EditorGUI.TextField(position, path);37 }38 }Objecttopathdrawer
public class ObjectToPathAttribute : PropertyAttribute{ public string _input; public ObjectToPathAttribute(string matchineName) { _input = matchineName; }}Objecttopathattribute
using UnityEngine;using System.Collections;public class UITest: MonoBehaviour{ [ObjectToPath("UITest)] public string _itemPerfabPath; // Use this for initialization void Start () { } // Update is called once per frame void Update () { }}
With the above code, you can drag and drop a prefab to store the corresponding path directly to the Public String _ itemperfabpath, eliminating the need for keyboard input steps. As follows:
When prefab is empty, the following statements are displayed:
Store the corresponding path by dragging the prefab