首页 > 代码库 > 编辑器显示自定义数据结构

编辑器显示自定义数据结构

  GUI/GUILayout/EditorGUILayout这几个类中没有提供自定义数据结构的显示,难道就不能像Inspector那样友好么,不然就只能使用基础元素来组合实现了。

  不赘述,代码如下:

public class TestClass{    public int value;    public string name = "";}public class TestEditor : EditorWindow{    public static TestEditor window = null;    [MenuItem("Test/MyEditor &t")]    public static void ShowWindow()    {        window = EditorWindow.GetWindow(typeof(TestEditor), false, "TestEditor") as TestEditor;    }    private List<TestClass> lst = new List<TestClass>();    private bool showFoldout = true;    private Vector2 scrollPosition = Vector2.zero;    int count    {        get { return lst.Count; }        set         {             if(value < lst.Count)            {                lst.RemoveRange(value, lst.Count - value);            }            else if(value > lst.Count)            {                for(int i = 0; i < value; ++i)                {                    lst.Add(new TestClass());                }            }        }    }    void OnGUI()    {        GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height), "", "box");        GUILayout.BeginVertical("box");        scrollPosition = GUILayout.BeginScrollView(scrollPosition, "box");      // 创建自适应滚动条        // 创建折叠标签        showFoldout = EditorGUILayout.Foldout(showFoldout, "Array");        if (showFoldout)        {            GUILayout.BeginHorizontal();            GUILayout.Label("count", GUILayout.Width(50));            count = System.Convert.ToInt32(GUILayout.TextField(count.ToString()));            GUILayout.EndHorizontal();            // 逐行显示数据            for (int i = 0; i < count; ++i)            {                GUILayout.BeginHorizontal();                GUILayout.Label("name", GUILayout.Width(50));                lst[i].name = GUILayout.TextField(lst[i].name);                GUILayout.Label("value", GUILayout.Width(50));                lst[i].value = System.Convert.ToInt32(GUILayout.TextField(lst[i].value.ToString()));                GUILayout.EndHorizontal();            }        }        GUILayout.EndVertical();        GUILayout.EndScrollView();        GUILayout.EndArea();    }}

  上述代码在自定义编辑器中显示了自定义结构TestClass的列表,效果如下所示:

  有个小细节值得一提,TestClass.name一定要初始化为"",不然现实会报错。

 

编辑器显示自定义数据结构