擴充套件Unity編輯器頂部Toolbar,增加自定義按鈕
阿新 • • 發佈:2022-03-05
因為遊戲需要增加幾種不同的啟動模式,想在編輯器頂部Toolbar處增加幾個按鈕。
由於Unity沒有直接提供介面,需要通過反射實現。看了下有一個開源庫:
https://github.com/marijnz/unity-toolbar-extender
感覺這樣有點複雜。因此我封裝了下,全都放在了一個類裡:
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; 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("Full setup")) { Debug.Log("Full setup"); } if (GUILayout.Button("Wramup setup")) { Debug.Log("Wramup setup"); } GUILayout.EndHorizontal(); } } }
效果: