Unity中的GUIStyle详解
2020-06-10 本文已影响0人
素颜悠悠
在平时项目开发中进行编辑器扩展是不可或缺的,拓展编辑器是一定需要创建各类组件。其中有一个需要提供的参数是GUIStyle参数,该参数可以让我们自定义组件的样式。比如,创建GUILayout.Button组件:
GUILayout.Button
GUIStyle可以new一个全新的实例,这样,需要自己处理所有自己需要的效果。
GUIStyle还可以基于已经存在的实例new一个新的实例,这样,只需对原有的效果中不符合自己需求的进行修改(省事省力,这类情况是我们最常用的),譬如:
GUIStyle btnStyle = new GUIStyle("Command");
btnStyle.fontSize = 12;
btnStyle.alignment = TextAnchor.MiddleCenter;
btnStyle.imagePosition = ImagePosition.ImageAbove;
btnStyle.fontStyle = FontStyle.Normal;
btnStyle.fixedWidth = 60;
//等同于:
GUIStyle btnStyle_1 = new GUIStyle("Command")
{
fontSize = 12,
alignment = TextAnchor.MiddleCenter,
imagePosition = ImagePosition.ImageAbove,
fontStyle = FontStyle.Normal,
fixedWidth = 60
};
那么到底怎么从内置的GUIStyle中找到自己想要的呢?
AssetStore里曾经有一个名为“Edior Style Viewer”的插件可以预览内置的所有GUIStyle,但是该插件已经下架。其实我们可以自己写一个脚本去查看,因为遍历 GUI.skin.customStyles 可以取到所有的内置GUIStyle,先上效果图:
(名字这一列是可以被选中复制的)话不多说,Editor下的代码如下:
using UnityEngine;
using UnityEditor;
public class GUIStyleViewer : EditorWindow {
Vector2 scrollPosition = new Vector2(0,0);
string search = "";
GUIStyle textStyle;
private static GUIStyleViewer window;
[MenuItem("Tool/GUIStyleViewer", false, 10)]
private static void OpenStyleViewer()
{
window = GetWindow<GUIStyleViewer>(false, "内置GUIStyle");
}
void OnGUI()
{
if (textStyle == null)
{
textStyle = new GUIStyle("HeaderLabel");
textStyle.fontSize = 25;
}
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();
}
}
接下来就是找到自己想要的样式稍作更改,用到自己写的拓展工具里啦~