1. 程式人生 > >Unity--PropertyAttribute和PropertyDrawer結合使用將string轉為資源引用

Unity--PropertyAttribute和PropertyDrawer結合使用將string轉為資源引用

程式碼如下:

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進行設定