扩展Unity编辑器顶部Toolbar,增加自定义按钮

游戏需要增加几种启动模式,要在编辑器顶部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();
        }
    }
}

 

效果:

 

posted @ 2022-03-05 14:58  HONT  阅读(1739)  评论(0编辑  收藏  举报