module-navigation-tool/Editor/Toolbar/ToolbarDrawer.cs

104 lines
3.1 KiB
C#

using Game.NavigationTool.Editor.Toolbar;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Game.NavigationTool.Editor
{
[InitializeOnLoad]
internal static class ToolbarDrawer
{
private static bool IS_INITIALIZED;
private static AbstractToolbarDrawer[] DRAWERS;
static ToolbarDrawer()
{
EditorApplication.update -= OnEditorUpdate;
EditorApplication.update += OnEditorUpdate;
}
private static void OnEditorUpdate()
{
if (!IS_INITIALIZED)
{
DRAWERS = ToolbarUtility.GetAllDrawers();
#if UNITY_2021_1_OR_NEWER
ToolbarUtility.OnUpdate(OnCreateElements);
#else
ToolbarUtility.AddGuiListener(OnGUI);
#endif
IS_INITIALIZED = true;
}
for (var i = 0; i < DRAWERS.Length; i++)
{
DRAWERS[i].Update();
}
}
#if UNITY_2021_1_OR_NEWER
private static void OnCreateElements(VisualElement leftAlign, VisualElement rightAlign)
{
const float HEIGHT = 22.0f;
for (var i = 0; i < DRAWERS.Length; i++)
{
AbstractToolbarDrawer drawer = DRAWERS[i];
var rect = new Rect(0.0f, 0.0f, drawer.CalculateWidth(), HEIGHT);
drawer.Setup(rect);
var container = new IMGUIContainer(drawer.OnGUI);
container.style.width = rect.width;
if (drawer.Placement == EToolbarPlacement.Left)
leftAlign.Add(container);
else
rightAlign.Add(container);
}
}
#else
private static void OnGUI()
{
const float Y = 5.0f;
const float SPACING = 4.0f;
const float HEIGHT = 22.0f;
const float PLAY_BUTTON_EXTENT = 75.0f;
const float PLAY_BUTTON_OFFSET = -23.0f;
if (DRAWERS == null)
return;
float xLeft = EditorGUIUtility.currentViewWidth * 0.5f + PLAY_BUTTON_OFFSET - PLAY_BUTTON_EXTENT;
float xRight = EditorGUIUtility.currentViewWidth * 0.5f + PLAY_BUTTON_OFFSET + PLAY_BUTTON_EXTENT;
for (var i = 0; i < DRAWERS.Length; i++)
{
AbstractToolbarDrawer drawer = DRAWERS[i];
GUI.enabled = drawer.Enabled;
float width = drawer.CalculateWidth();
Rect rect;
if (drawer.Placement == EToolbarPlacement.Left)
{
rect = new Rect(xLeft - width, Y, width, HEIGHT);
xLeft -= width + SPACING;
}
else
{
rect = new Rect(xRight, Y, width, HEIGHT);
xRight += width + SPACING;
}
drawer.Setup(rect);
drawer.OnGUI();
}
GUI.enabled = true;
}
#endif
}
}