在平時項目開發中進行編輯器擴展是不可或缺的,拓展編輯器是一定需要創建各類組件。其中有一個需要提供的參數是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();
}
}
接下來就是找到自己想要的樣式稍作更改,用到自己寫的拓展工具里啦~