代码如下:
using UnityEngine;
public class PropertyTest : MonoBehaviour
{
public string prefabPath = "";
}
prefabPath表示引用的prefab路径,在Inspector中显示如下图
这种情况需要手动填写prefab的路径,填错prefab路径程序运行就找不到prefab了,下面通过
PropertyAttribute和PropertyDrawer结合,在Inspector中显示出来的是资源引用,直接弹出面板选择prefab
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(PrefabReference))]
public class ResReferenceDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (SerializedPropertyType.String != property.propertyType)
{
EditorGUI.PropertyField(position, property);
return;
}
//根据路径得到一个类型为GameObject的对象
var prefab = (GameObject)AssetDatabase.LoadAssetAtPath(property.stringValue, typeof(GameObject));
//ObjectField会在Inspector面板中显示一个框,后面带一个小按钮,点击后弹出面板选择prefab
var obj = (GameObject)EditorGUI.ObjectField(position, property.displayName, prefab, typeof(GameObject), false);
//得到prefab的路径
string newPath = AssetDatabase.GetAssetPath(obj);
//设置路径
property.stringValue = newPath;
Debug.Log(newPath);
}
}
效果如图,可以点击后面按钮弹出面板选择,也可以直接拖拽prefab进行设置