在写 EditorWindow 或者 Inspector 面板时,常常需要用到各种控件和样式,于是,一个方便查询 GUIStyle 的功能应运而生了。先看一下效果:


窗口里列举了各类样式的 Label Button 及其他各种控件的名称。这个名称是可以以字符串的形式用作 GUIStyle 参数的。
首先是菜单入口的代码:
[MenuItem("客户端/查看内置 GUI Style...", false, 540)]
public static void OpenGUIStyleViewer()
{
GUIStyleViewer guiStyleViewer = new GUIStyleViewer();
guiStyleViewer.Show();
}
实现这里核心的逻辑就是从 GUI.skin.customStyles 拿到所有的 GUIStyle 列表,然后创建一个滚动列表,将每一个样式作为一个 Button 的样式显示出来。
完整代码如下:
using UnityEngine;
using UnityEditor;
public class GUIStyleViewer : EditorWindow
{
Vector2 scrollPosition = new(0, 0);
string search = "";
GUIStyle textStyle;
private static GUIStyleViewer _window;
private static void OpenStyleViewer()
{
_window = GetWindow<GUIStyleViewer>(false, "查看内置 GUIStyle");
}
void OnGUI()
{
if (textStyle == null)
{
textStyle = new GUIStyle("HeaderLabel") { fontSize = 20 };
}
GUILayout.BeginHorizontal("HelpBox");
GUILayout.Label("点击示例,可以将其名字复制下来", textStyle);
GUILayout.FlexibleSpace();
GUILayout.Label("Search:");
search = EditorGUILayout.TextField(search);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal("PopupCurveSwatchBackground");
GUILayout.Label("示例", textStyle, GUILayout.Width(300));
GUILayout.Label("名字", textStyle, GUILayout.Width(300));
GUILayout.EndHorizontal();
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
foreach (var style in GUI.skin.customStyles)
{
if (style.name.ToLower().Contains(search.ToLower()))
{
GUILayout.Space(15);
GUILayout.BeginHorizontal("PopupCurveSwatchBackground");
if (GUILayout.Button(style.name, style, GUILayout.Width(300)))
{
EditorGUIUtility.systemCopyBuffer = style.name;
Debug.LogError(style.name);
}
EditorGUILayout.SelectableLabel(style.name, GUILayout.Width(300));
GUILayout.EndHorizontal();
}
}
GUILayout.EndScrollView();
}
}