TreeView
?
用于显示可以展开和折叠的层级数据。
IMGUI.Controls.TreeView - Unity 脚本 APIhttps://docs.unity.cn/cn/2020.3/ScriptReference/IMGUI.Controls.TreeView.html
代码示例
SimpleTreeView.cs
using System.Collections.Generic;
using UnityEditor.IMGUI.Controls;
class SimpleTreeView : TreeView
{
public SimpleTreeView(TreeViewState treeViewState)
: base(treeViewState)
{
// 每次调用 Reload 时都调用 BuildRoot,从而确保使用数据
Reload();
}
protected override TreeViewItem BuildRoot()
{
// 此部分说明 ID 应该是唯一的。根项的深度
// 必须为 -1,其余项的深度在此基础上递增。
var root = new TreeViewItem { id = 0, depth = -1, displayName = "Root" };
var allItems = new List<TreeViewItem>
{
new TreeViewItem {id = 1, depth = 0, displayName = "Animals"},
new TreeViewItem {id = 2, depth = 1, displayName = "Mammals"},
new TreeViewItem {id = 3, depth = 2, displayName = "Tiger"},
new TreeViewItem {id = 4, depth = 2, displayName = "Elephant"},
new TreeViewItem {id = 5, depth = 2, displayName = "Okapi"},
new TreeViewItem {id = 6, depth = 2, displayName = "Armadillo"},
new TreeViewItem {id = 7, depth = 1, displayName = "Reptiles"},
new TreeViewItem {id = 8, depth = 2, displayName = "Crocodile"},
new TreeViewItem {id = 9, depth = 2, displayName = "Lizard"},
};
// 用于初始化所有项的 TreeViewItem.children 和 .parent 的实用方法。
SetupParentsAndChildrenFromDepths(root, allItems);
return root;
}
}
SimpleTreeViewWindow.cs
using UnityEngine;
using UnityEditor.IMGUI.Controls;
using UnityEditor;
class SimpleTreeViewWindow : EditorWindow
{
// SerializeField 用于确保将视图状态写入窗口
// 布局文件。这意味着只要窗口未关闭,即使重新启动 Unity,也会保持
// 状态。如果省略该属性,仍然会序列化/反序列化状态。
[SerializeField] TreeViewState m_TreeViewState;
//TreeView 不可序列化,因此应该通过树数据对其进行重建。
SimpleTreeView m_TreeView;
SearchField m_SearchField;
void OnEnable()
{
//检查是否已存在序列化视图状态(在程序集重新加载后
// 仍然存在的状态)
if (m_TreeViewState == null)
m_TreeViewState = new TreeViewState();
m_TreeView = new SimpleTreeView(m_TreeViewState);
m_SearchField = new SearchField();
m_SearchField.downOrUpArrowKeyPressed += m_TreeView.SetFocusAndEnsureSelectedItem;
}
void OnGUI()
{
DoToolbar();
DoTreeView();
}
//搜索框
void DoToolbar()
{
GUILayout.BeginHorizontal(EditorStyles.toolbar);
GUILayout.Space(100);
GUILayout.FlexibleSpace();
m_TreeView.searchString = m_SearchField.OnToolbarGUI(m_TreeView.searchString);
GUILayout.EndHorizontal();
}
//绘制TreeView
void DoTreeView()
{
Rect rect = GUILayoutUtility.GetRect(0, 100000, 0, 100000);
m_TreeView.OnGUI(rect);
}
[MenuItem("TreeView Examples/Simple Tree Window")]
static void ShowWindow()
{
var window = GetWindow<SimpleTreeViewWindow>();
window.titleContent = new GUIContent("My Window");
window.Show();
}
}
?实现效果
编辑器免费课程:
独立游戏《Unity打造关卡编辑器》Unity 独立游戏 关卡编辑器https://bycwedu.vipwan.cn/promotion_channels/72762192?
|