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一定要初始化为"",不然现实会报错。
添加Project界面自定义菜单:
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName="Test/CreateMyObject")] public class MyObject : ScriptableObject { // 中心点 public Vector3 Center; // 受击点 public List<Vector3> HitPos = new List<Vector3>(); // 受击点朝向 public List<Vector3> HitDir = new List<Vector3>(); }
获取Hierarchy中gameobject所关联的本地资源prefab:
var prefabSource = PrefabUtility.GetPrefabParent(prefab);
本文介绍如何在Unity中通过自定义编辑器显示自定义数据结构。以TestClass为例,展示了如何利用GUI、GUILayout和EditorGUILayout类创建可滚动的界面,并通过Foldout组件控制显示详细数据。同时介绍了如何在Project面板中添加自定义菜单项。
1051

被折叠的 条评论
为什么被折叠?



