Files
2026-05-08 18:21:51 +01:00

143 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
using Godot;
using Tutorials.addons.custom_inspector_tools.InspectorPlugins;
namespace Tutorials.addons.custom_inspector_tools;
#if TOOLS
[Tool]
public partial class CustomInspectorPlugin : EditorPlugin
{
private readonly List<EditorInspectorPlugin> _customPlugins = new();
private bool _pluginsBuilt = false;
private bool _inspectorPluginsAdded = false;
private EditorSelection _selection;
private bool _refreshingInspector = false;
public override void _EnterTree()
{
base._EnterTree();
if (!_pluginsBuilt)
{
BuildPlugins();
_pluginsBuilt = true;
}
_selection = EditorInterface.Singleton.GetSelection();
_selection.SelectionChanged += OnSelectionChanged;
}
private void OnSelectionChanged()
{
if (!_inspectorPluginsAdded)
{
return;
}
RefreshInspectorForCurrentSelection();
}
private void RefreshInspectorForCurrentSelection()
{
if (_refreshingInspector)
{
return;
}
_refreshingInspector = true;
try
{
GodotObject objToInspect = null;
foreach (var node in _selection.GetSelectedNodes())
{
if (node is not null)
{
objToInspect = node;
break;
}
}
// Drop old inspector UI, then rebuild for the selected object.
EditorInterface.Singleton.InspectObject(null);
if (objToInspect is not null)
{
EditorInterface.Singleton.InspectObject(objToInspect);
}
}
finally
{
_refreshingInspector = false;
}
}
private void BuildPlugins()
{
_customPlugins.Clear();
// Add new plugins here as you create them.
_customPlugins.Add(new TestBoxInspectorPlugin());
}
public override void _EnablePlugin()
{
base._EnablePlugin();
try
{
if (_inspectorPluginsAdded)
return;
foreach (var plugin in _customPlugins)
{
AddInspectorPlugin(plugin);
GD.Print($"Added inspector plugin: {plugin.GetType().Name}");
}
_inspectorPluginsAdded = true;
RefreshInspectorForCurrentSelection();
}
catch (Exception ex)
{
GD.PrintErr($"Error enabling CustomInspectorPlugin: {ex.Message}");
}
}
public override void _DisablePlugin()
{
try
{
RemoveAllInspectorPlugins();
EditorInterface.Singleton.InspectObject(null);
RefreshInspectorForCurrentSelection();
}
catch (Exception ex)
{
GD.PrintErr($"Error disabling CustomInspectorPlugin: {ex.Message}");
}
base._DisablePlugin();
}
private void RemoveAllInspectorPlugins()
{
if (!_inspectorPluginsAdded)
return;
foreach (var plugin in _customPlugins)
{
RemoveInspectorPlugin(plugin);
GD.Print($"Removed inspector plugin: {plugin.GetType().Name}");
}
_inspectorPluginsAdded = false;
}
}
#endif