Unity自定義ScriptableObject屬性顯示的三種方式

1. 繼承Editor提澎,重寫OnInspectorGUI方法

Editor官方文檔

效果

實(shí)現(xiàn)

定義一個(gè)測試類TestClass诉濒,一個(gè)可序列化類DataClass

[CreateAssetMenu]
public class TestClass : ScriptableObject
{
    [Range(0, 10)]
    public int intData;
    public string stringData;
    public List<DataClass> dataList;
}

[System.Serializable]
public class DataClass
{
    [Range(0, 100)]
    public int id;
    public Vector3 position;
    public List<int> list;
}
//指定類型
[CustomEditor(typeof(TestClass))]
public class TestClassEditor  : Editor
{
    SerializedProperty intField;
    SerializedProperty stringField;

    void OnEnable()
    {
        //獲取指定字段
        intField = serializedObject.FindProperty("intData");
        stringField = serializedObject.FindProperty("stringData");
    }

    public override void OnInspectorGUI()
    {
        // Update the serializedProperty - always do this in the beginning of OnInspectorGUI.
        serializedObject.Update();
        EditorGUILayout.IntSlider(intField, 0, 100, new GUIContent("initData"));
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.PropertyField(stringField);
        if(GUILayout.Button("Select"))
        {
            stringField.stringValue = EditorUtility.OpenFilePanel("", Application.dataPath, "");
        }
        EditorGUILayout.EndHorizontal();

        // Apply changes to the serializedProperty - always do this in the end of OnInspectorGUI.
        //需要在OnInspectorGUI之前修改屬性板祝,否則無法修改值
        serializedObject.ApplyModifiedProperties();
        
        base.OnInspectorGUI();
    }
}

Editor嵌套

通過Edtiro.CreateEditor可實(shí)現(xiàn)Editor的嵌套悬嗓。

創(chuàng)建一個(gè)類TestClass2顾稀,它包含一個(gè)TestClass的屬性博肋。

[CreateAssetMenu]
public class TestClass2 : ScriptableObject
{
    public TestClass data;
}

創(chuàng)建一個(gè)Test2Class的asset。它的Inspector面板的默認(rèn)顯示:


它并沒有把TestClass的屬性顯示出來赃春,如果要查看TestClass的屬性蜻底,必須雙擊,跳到相應(yīng)界面聘鳞,但這樣有看不到TestClass2的屬性薄辅。

如果想在Test2Class的Inspector面板中直接看到并且可以修改TestClass的屬性,可以重寫TestClass2的Editor抠璃,并在其中嵌套TestClass的Editor站楚。

[CustomEditor(typeof(TestClass2))]
public class TestClass2Editor : Editor
{
    Editor cacheEditor;
    public override void OnInspectorGUI()
    {
        // Update the serializedProperty - always do this in the beginning of OnInspectorGUI.
        serializedObject.Update();
        //顯示TestClass2的默認(rèn)UI
        base.OnInspectorGUI();

        GUILayout.Space(20);
        var data = ( (TestClass2)target ).data;
        if(data != null)
        {
            //創(chuàng)建TestClass的Editor
            if (cacheEditor == null)
                cacheEditor = Editor.CreateEditor(data);
            GUILayout.Label("this is TestClass2");
            cacheEditor.OnInspectorGUI();
        }
    }
}

這樣就可以直接在TestClass2的面板中直接查看和編輯TestClass的屬性。

2. 使用PropertyDrawer

PropertyDrawer官方文檔

如果想修改某種特定類型的顯示搏嗡,使用繼承Editor的方式就會(huì)變得很麻煩窿春,因?yàn)樗惺褂锰囟愋偷腶sset都需要去實(shí)現(xiàn)一個(gè)自定義的Editor,效率非常低采盒。這種情況就可以通過繼承PropertyDrawer的方式旧乞,對指定類型的屬性,進(jìn)行統(tǒng)一顯示磅氨。

效果

為Inspector面板中的所有string屬性添加一個(gè)選擇文件按鈕尺栖,選中文件的路徑直接賦值給該變量。


實(shí)現(xiàn)

[CustomPropertyDrawer(typeof(string))]
public class StringPropertyDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        Rect btnRect = new Rect(position);
        position.width -= 60;
        btnRect.x += btnRect.width - 60;
        btnRect.width = 60;
        EditorGUI.BeginProperty(position, label, property);
        EditorGUI.PropertyField(position, property, true);
        if (GUI.Button(btnRect, "select"))
        {
            string path = property.stringValue;
            string selectStr = EditorUtility.OpenFilePanel("選擇文件", path, "");
            if (!string.IsNullOrEmpty(selectStr))
            {
                property.stringValue = selectStr;
            }
        }

        EditorGUI.EndProperty();
    }
}

加了一個(gè)PropertyDrawer之后烦租,Inspector面板中的所有string變量都會(huì)額外添加一個(gè)Select按鈕延赌。

注意事項(xiàng)

  1. PropertyDrawer只對可序列化的類有效除盏,非可序列化的類沒法在Inspector面板中顯示。
  2. OnGUI方法里只能使用GUI相關(guān)方法挫以,不能使用Layout相關(guān)方法者蠕。
  3. PropertyDrawer對應(yīng)類型的所有屬性的顯示方式都會(huì)修改,例如創(chuàng)建一個(gè)帶string屬性的MonoBehaviour:

3. 使用PropertyAttribute

PropertyAttribute官方文檔

如果想要修改部分類的指定類型的屬性的顯示掐松,直接使用PropertyDrawer就無法滿足條件踱侣,這時(shí)可以結(jié)合PropertyAttribute和PropertyAttribute來實(shí)現(xiàn)需求。

效果

為部分指定類的int或float屬性的顯示添加滑動(dòng)條大磺,滑動(dòng)條的上下限可根據(jù)類和屬性自行設(shè)置抡句。

實(shí)現(xiàn)

public class RangeAttribute : PropertyAttribute
{
    public float min;
    public float max;

    public RangeAttribute(float min, float max)
    {
        this.min = min;
        this.max = max;
    }
}

[CustomPropertyDrawer(typeof(RangeAttribute))]
public class RangeDrawer : PropertyDrawer
{
    // Draw the property inside the given rect
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        // First get the attribute since it contains the range for the slider
        RangeAttribute range = attribute as RangeAttribute;

        // Now draw the property as a Slider or an IntSlider based on whether it's a float or integer.
        if (property.propertyType == SerializedPropertyType.Float)
            EditorGUI.Slider(position, property, range.min, range.max, label);
        else if (property.propertyType == SerializedPropertyType.Integer)
            EditorGUI.IntSlider(position, property, (int)range.min, (int)range.max, label);
        else
            EditorGUI.LabelField(position, label.text, "Use Range with float or int.");
    }
}

修改TestClass和DataClass

[CreateAssetMenu]
public class TestClass : ScriptableObject
{
    [Range(0, 10)]
    public int intData;
    public string stringData;
    public List<DataClass> dataList;
}

[System.Serializable]
public class DataClass
{
    [Range(0, 100)]
    public int id;
    public Vector3 position;
    public List<int> list;
}

其他

  • 需要修改顯示的類都需要滿足Unity的序列化規(guī)則
  • 這幾種顯示方式對Serializable Class都可以使用,并不需要一定是ScriptableObject量没。只是在編輯器下玉转,ScriptableObject來保存臨時(shí)數(shù)據(jù)比較常用突想,所以使用ScriptableObject來做例子殴蹄。

demo下載

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市猾担,隨后出現(xiàn)的幾起案子袭灯,更是在濱河造成了極大的恐慌,老刑警劉巖绑嘹,帶你破解...
    沈念sama閱讀 216,997評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件稽荧,死亡現(xiàn)場離奇詭異,居然都是意外死亡工腋,警方通過查閱死者的電腦和手機(jī)姨丈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來擅腰,“玉大人蟋恬,你說我怎么就攤上這事〕酶裕” “怎么了歼争?”我有些...
    開封第一講書人閱讀 163,359評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長渗勘。 經(jīng)常有香客問我沐绒,道長,這世上最難降的妖魔是什么旺坠? 我笑而不...
    開封第一講書人閱讀 58,309評(píng)論 1 292
  • 正文 為了忘掉前任乔遮,我火速辦了婚禮,結(jié)果婚禮上取刃,老公的妹妹穿的比我還像新娘申眼。我一直安慰自己瞒津,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評(píng)論 6 390
  • 文/花漫 我一把揭開白布括尸。 她就那樣靜靜地躺著巷蚪,像睡著了一般。 火紅的嫁衣襯著肌膚如雪濒翻。 梳的紋絲不亂的頭發(fā)上屁柏,一...
    開封第一講書人閱讀 51,258評(píng)論 1 300
  • 那天,我揣著相機(jī)與錄音有送,去河邊找鬼淌喻。 笑死,一個(gè)胖子當(dāng)著我的面吹牛雀摘,可吹牛的內(nèi)容都是我干的裸删。 我是一名探鬼主播,決...
    沈念sama閱讀 40,122評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼阵赠,長吁一口氣:“原來是場噩夢啊……” “哼涯塔!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起清蚀,我...
    開封第一講書人閱讀 38,970評(píng)論 0 275
  • 序言:老撾萬榮一對情侶失蹤匕荸,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后枷邪,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體榛搔,經(jīng)...
    沈念sama閱讀 45,403評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評(píng)論 3 334
  • 正文 我和宋清朗相戀三年东揣,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了践惑。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,769評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡嘶卧,死狀恐怖尔觉,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情脸候,我是刑警寧澤穷娱,帶...
    沈念sama閱讀 35,464評(píng)論 5 344
  • 正文 年R本政府宣布,位于F島的核電站运沦,受9級(jí)特大地震影響泵额,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜携添,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評(píng)論 3 327
  • 文/蒙蒙 一嫁盲、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦羞秤、人聲如沸缸托。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽俐镐。三九已至,卻和暖如春哺哼,著一層夾襖步出監(jiān)牢的瞬間佩抹,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評(píng)論 1 269
  • 我被黑心中介騙來泰國打工取董, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留棍苹,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,831評(píng)論 2 370
  • 正文 我出身青樓茵汰,卻偏偏與公主長得像枢里,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子蹂午,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容