unity 在toolbar处添加按钮

 

 

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("热重载", EditorGUIUtility.FindTexture("PlayButton"))))
        {
            Debug.Log("HotReload");
            BuildAssemblieEditor.BuildLogic();
        }

        GUILayout.EndHorizontal();
    }
}

 

 

 https://github.com/smkplus/CustomToolbar

 

这个很不错,而且轻量化,推荐

视频:https://www.youtube.com/watch?v=NBARPT-APCg 

https://github.com/marijnz/unity-toolbar-extender

posted @ 2023-03-19 11:35  三页菌  阅读(97)  评论(0编辑  收藏  举报