Unity3D編輯器擴展(七)—— 在自定義編輯器窗口中序列化List對象


假設我們創建一個 Test 組件,並定義一個 string 類型的列表,代碼如下:

1 using System.Collections.Generic;
2 using UnityEngine;
3 
4 public class Test : MonoBehaviour 
5 {
6     public List<string> strs;
7 }

掛載組件后,我們會得到下面的效果:

 

 Unity 自動幫我們把 strs 這個 List 序列化到了面板上,我們還可以通過修改 Size 的大小,來改變 List 的大小,也可以通過鼠標右鍵來刪除或者復制一個元素。

如果我們想要在自定義的窗口中去序列化一個 List 對象應該怎么做呢?

這時,我們就需要用到 SerializedObject 和 SerializedProperty 兩個類來幫助我們序列化,代碼如下:

 1 using System.Collections.Generic;
 2 using UnityEditor;
 3 using UnityEngine;
 4 
 5 public class EditorTest : EditorWindow
 6 {
 7     public List<string> stringList = new List<string>();
 8 
 9     private SerializedObject serializedObject;
10     private SerializedProperty serializedProperty;
11 
12     [MenuItem("MyEditor/Window1")]
13     private static void Window()
14     {
15         EditorTest _editorTest = (EditorTest)EditorWindow.GetWindow(typeof(EditorTest), false, "Window", true);
16         _editorTest.Show();
17     }
18 
19     private void OnEnable()
20     {
21         serializedObject = new SerializedObject(this);
22         serializedProperty = serializedObject.FindProperty("stringList");
23     }
24     private void OnGUI()
25     {
26         serializedObject.Update();
27         EditorGUI.BeginChangeCheck();
28         EditorGUILayout.PropertyField(serializedProperty, true);
29         if (EditorGUI.EndChangeCheck())
30         {
31             serializedObject.ApplyModifiedProperties();
32         }
33 
34         GUILayout.BeginHorizontal();
35         GUILayout.FlexibleSpace();//插入一個彈性空白  
36         if (GUILayout.Button("Add"))
37         {
38             stringList.Add(string.Empty);
39         }
40         GUILayout.EndHorizontal();
41     }
42 }

我們會得到下面的效果:

 

 這樣我們就實現了再窗口中序列化 List 對象。這里還實現了一個 Add 按鈕去方便我們新增元素,至於刪除,還是得使用鼠標右鍵。

如果說我們 List 中存儲的是我們自定義的數據類型,那么這個類型必須添加 [System.Serializable] 標簽,否則無法序列化。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM