游戲需要增加幾種啟動模式,要在編輯器頂部Toolbar處增加幾個按鈕;進行下擴展。
這部分Unity沒有直接提供接口,需通過反射實現。看了下有一個開源庫:
https://github.com/marijnz/unity-toolbar-extender
(2022/12/25補充一個完成度更高的開源庫:https://github.com/smkplus/CustomToolbar)
但感覺還要用到額外的庫有點復雜,干脆都放在一個類里封裝下(unity2021.x):
namespace Hont { using System; using System.Reflection; using UnityEngine; using UnityEditor; using UnityEngine.UIElements; [InitializeOnLoad] public static class CruToolbar { private static readonly Type kToolbarType = typeof(Editor).Assembly.GetType("UnityEditor.Toolbar"); private static ScriptableObject sCurrentToolbar; static CruToolbar() { EditorApplication.update += OnUpdate; } private static void OnUpdate() { if (sCurrentToolbar == null) { UnityEngine.Object[] toolbars = Resources.FindObjectsOfTypeAll(kToolbarType); sCurrentToolbar = toolbars.Length > 0 ? (ScriptableObject)toolbars[0] : null; if (sCurrentToolbar != null) { FieldInfo root = sCurrentToolbar.GetType().GetField("m_Root", BindingFlags.NonPublic | BindingFlags.Instance); VisualElement concreteRoot = root.GetValue(sCurrentToolbar) as VisualElement; VisualElement toolbarZone = concreteRoot.Q("ToolbarZoneRightAlign"); VisualElement parent = new VisualElement() { style = { flexGrow = 1, flexDirection = FlexDirection.Row, } }; IMGUIContainer container = new IMGUIContainer(); container.onGUIHandler += OnGuiBody; parent.Add(container); toolbarZone.Add(parent); } } } private static void OnGuiBody() { //自定義按鈕加在此處 GUILayout.BeginHorizontal(); if (GUILayout.Button(new GUIContent("Full setup", EditorGUIUtility.FindTexture("PlayButton")))) { Debug.Log("Full setup"); } if (GUILayout.Button(new GUIContent("Wram-up setup", EditorGUIUtility.FindTexture("PlayButton")))) { Debug.Log("Wram-up setup"); } GUILayout.EndHorizontal(); } } }
效果:

