具有层次结构的自定义窗口

时间:2014-11-20 16:03:37

标签: c# unity3d

我正在构建一个自定义窗口,我想模仿Unity的Hierarchy并将其添加到我的窗口。

这是我到目前为止所做的,我想要做的是将子对象和父对象组合在一起,就像在Unity的编辑器中一样。目前它只是将场景中的每个对象列为没有子项的列表。如何让它看起来像Unity的层次结构视图?

void OnGUI() {
    EditorGUILayout.BeginHorizontal(); 
    {
        scroll = EditorGUILayout.BeginScrollView(scroll, GUILayout.Width(200), GUILayout.Height(500));
        {
            GameObject[] gameObjects = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
            foreach (GameObject go in gameObjects) {
                EditorGUILayout.Foldout(false, go.name);
            }
        }
        EditorGUILayout.EndScrollView();
    }
    EditorGUILayout.EndHorizontal();
}

1 个答案:

答案 0 :(得分:1)

您可以这样做:

void OnGUI() {
    EditorGUILayout.BeginHorizontal();
    {
        scroll = EditorGUILayout.BeginScrollView(scroll, GUILayout.Width(200), GUILayout.Height(500));
        {
            GameObject[] gameObjects = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
            foreach (GameObject go in gameObjects) {
                // Start with game objects without any parents
                if (go.transform.parent == null) {
                    // Show the object and its children
                    ShowObject(go, gameObjects);
                }
            }
        }
        EditorGUILayout.EndScrollView();
    }
    EditorGUILayout.EndHorizontal();
}

void ShowObject(GameObject parent, GameObject[] gameObjects) {
    // Show entry for parent object
    if (UnityEditor.EditorGUILayout.Foldout(IsEntryOpen(parent), parent.name)) {
        foreach (GameObject go in gameObjects) {
            // Find children of the parent game object
            if (go.transform.parent == parent.transform) {
                ShowObject(go, gameObjects);
            }
        }
    }
}

请注意,您还需要一种方法来跟踪打开的对象条目(实现IsEntryOpen()方法)。为此,您可以拥有一个List,如果Foldout()返回true,则将GameObjects添加到此列表中,如果返回false则删除。

您还希望以某种方式缩进子对象。一种方法是将它们包装在GUILayout.BeginHorizontal()GUILayout.BeginVertical()中,并使用GUILayout.Space()缩进。