feat: Round 48 narrative systems improvements

- QuestSO: Add ValidateBranchCycles() DFS detection for branches[].nextQuest loop
- QuestSO: Mark three legacy prerequisite fields with v2.0 removal warning in Tooltip
- IQuestManager: Add QuestLockReason enum + QuestLockInfo struct (strongly-typed lock info)
- IQuestManager: Add GetQuestLockInfo() method to interface; GetQuestLockReason() now delegates to it
- IQuestEventSource: Add OnQuestStateChanged(questId, oldState, newState) unified event
- QuestManager: Implement GetQuestLockInfo(); fire OnQuestStateChanged on all state transitions
- DialogueManager: Add one-frame yield in HandleChoices before ShowChoices (skip-debounce fix)
- DialogueManager: Increment _playbackId in ForceEnd() to invalidate residual choice callbacks
- DialogueSequenceSO: Add UNITY_EDITOR debug log in TryGetActiveVariant on variant match
- WorldStateRegistry: Add OnBatchStateChanged event + BatchMark() batch-write API
- DialogueModule: List badge shows warning indicator for unconditional-shadowing variants
- DialogueModule: BuildVariantsCard shows logic mode (AND/OR) alongside flag conditions

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-05-25 00:05:15 +08:00
parent 446fd5dcd0
commit 6eaa83dc71
72 changed files with 7080 additions and 373 deletions

View File

@@ -33,6 +33,7 @@
"BaseGames.World.Streaming",
"BaseGames.EventChain",
"BaseGames.VFX",
"BaseGames.Localization",
"Unity.InputSystem"
],
"includePlatforms": [

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 76d7c0ea7917c4444b0eede5ed06e14c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,379 @@
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using BaseGames.Dialogue;
namespace BaseGames.Editor.Dialogue
{
/// <summary>
/// 对话变体预览窗口。
/// 给定一个 DialogueSequenceSO模拟世界状态标志的开关组合
/// 实时显示各条件变体是否满足,并高亮胜出的变体。
/// 菜单BaseGames/Dialogue/Variant Preview
/// </summary>
public class DialogueVariantPreviewWindow : EditorWindow
{
private DialogueSequenceSO _target;
private readonly HashSet<string> _enabledFlags = new(System.StringComparer.Ordinal);
private readonly List<string> _allFlags = new();
private ObjectField _targetField;
private VisualElement _flagContainer;
private VisualElement _resultContainer;
private static readonly Color ColWin = new(0.20f, 0.75f, 0.35f, 1f);
private static readonly Color ColFail = new(0.55f, 0.55f, 0.55f, 1f);
private static readonly Color ColOverride = new(0.70f, 0.70f, 0.25f, 1f);
private static readonly Color ColBlocked = new(0.85f, 0.35f, 0.30f, 1f);
[MenuItem("BaseGames/Dialogue/Variant Preview")]
public static void Open()
{
var win = GetWindow<DialogueVariantPreviewWindow>("对话变体预览");
win.minSize = new Vector2(480, 400);
}
/// <summary>从外部打开并预填目标 SO。</summary>
public static void OpenWith(DialogueSequenceSO target)
{
var win = GetWindow<DialogueVariantPreviewWindow>("对话变体预览");
win.minSize = new Vector2(480, 400);
win.SetTarget(target);
}
private void CreateGUI()
{
_mockReader = new MockFlagReader(_enabledFlags);
rootVisualElement.style.paddingLeft = 10;
rootVisualElement.style.paddingRight = 10;
rootVisualElement.style.paddingTop = 10;
rootVisualElement.style.paddingBottom = 10;
// ── 标题栏 ──
var header = new Label("对话变体预览工具");
header.style.fontSize = 14;
header.style.unityFontStyleAndWeight = FontStyle.Bold;
header.style.marginBottom = 8;
rootVisualElement.Add(header);
var desc = new Label("在模拟的世界状态标志组合下,预览哪个条件变体会被选中。");
desc.style.fontSize = 11;
desc.style.opacity = 0.6f;
desc.style.marginBottom = 10;
rootVisualElement.Add(desc);
// ── 目标选择器 ──
_targetField = new ObjectField("对话序列 SO")
{
objectType = typeof(DialogueSequenceSO),
allowSceneObjects = false
};
_targetField.value = _target;
_targetField.RegisterValueChangedCallback(evt =>
{
SetTarget(evt.newValue as DialogueSequenceSO);
});
rootVisualElement.Add(_targetField);
rootVisualElement.Add(MakeDivider());
// ── 标志模拟区 ──
var flagHeader = new Label("模拟世界状态标志");
flagHeader.style.fontSize = 12;
flagHeader.style.unityFontStyleAndWeight = FontStyle.Bold;
flagHeader.style.marginBottom = 4;
rootVisualElement.Add(flagHeader);
_flagContainer = new VisualElement();
rootVisualElement.Add(_flagContainer);
rootVisualElement.Add(MakeDivider());
// ── 变体结果区 ──
var resultHeader = new Label("变体求值结果");
resultHeader.style.fontSize = 12;
resultHeader.style.unityFontStyleAndWeight = FontStyle.Bold;
resultHeader.style.marginBottom = 4;
rootVisualElement.Add(resultHeader);
var scrollView = new ScrollView(ScrollViewMode.Vertical);
scrollView.style.flexGrow = 1;
rootVisualElement.Add(scrollView);
_resultContainer = new VisualElement();
scrollView.Add(_resultContainer);
Rebuild();
}
private void SetTarget(DialogueSequenceSO target)
{
_target = target;
_enabledFlags.Clear();
if (_targetField != null && _targetField.value != target)
_targetField.SetValueWithoutNotify(target);
Rebuild();
}
// ── 重建 ─────────────────────────────────────────────────────────────
private void Rebuild()
{
RebuildFlagToggles();
RebuildResults();
}
private void RebuildFlagToggles()
{
if (_flagContainer == null) return;
_flagContainer.Clear();
_allFlags.Clear();
if (_target == null || _target.variants == null || _target.variants.Length == 0)
{
var empty = new Label(_target == null
? "(请选择一个 DialogueSequenceSO"
: "(该序列无条件变体,无需模拟)");
empty.style.opacity = 0.5f;
empty.style.fontSize = 11;
_flagContainer.Add(empty);
return;
}
// 收集所有变体中涉及的 Flag
var flagSet = new HashSet<string>(System.StringComparer.Ordinal);
foreach (var v in _target.variants)
{
if (v.requiredFlags != null)
foreach (var f in v.requiredFlags)
if (!string.IsNullOrEmpty(f)) flagSet.Add(f);
}
_allFlags.AddRange(flagSet.OrderBy(x => x));
if (_allFlags.Count == 0)
{
var empty = new Label("(变体未使用任何 requiredFlags");
empty.style.opacity = 0.5f;
empty.style.fontSize = 11;
_flagContainer.Add(empty);
return;
}
// 全选 / 全不选 快速按钮
var btnRow = new VisualElement();
btnRow.style.flexDirection = FlexDirection.Row;
btnRow.style.marginBottom = 4;
var btnAll = new Button(() =>
{
foreach (var f in _allFlags) _enabledFlags.Add(f);
Rebuild();
}) { text = "全选" };
btnAll.style.fontSize = 10;
btnAll.style.height = 18;
btnRow.Add(btnAll);
var btnNone = new Button(() =>
{
_enabledFlags.Clear();
Rebuild();
}) { text = "全不选" };
btnNone.style.fontSize = 10;
btnNone.style.height = 18;
btnRow.Add(btnNone);
_flagContainer.Add(btnRow);
// 每个 Flag 对应一个 Toggle
foreach (var flag in _allFlags)
{
bool isOn = _enabledFlags.Contains(flag);
var toggle = new Toggle(flag) { value = isOn };
toggle.style.fontSize = 11;
toggle.RegisterValueChangedCallback(evt =>
{
if (evt.newValue) _enabledFlags.Add(flag);
else _enabledFlags.Remove(flag);
RebuildResults();
});
_flagContainer.Add(toggle);
}
}
private void RebuildResults()
{
if (_resultContainer == null) return;
_resultContainer.Clear();
if (_target == null)
return;
if (_target.variants == null || _target.variants.Length == 0)
{
var msg = new Label("(序列无条件变体,直接使用本序列默认台词)");
msg.style.opacity = 0.5f;
msg.style.fontSize = 11;
_resultContainer.Add(msg);
return;
}
bool winnerFound = false;
for (int i = 0; i < _target.variants.Length; i++)
{
var variant = _target.variants[i];
var row = BuildVariantRow(i, variant, winnerFound);
_resultContainer.Add(row);
if (!winnerFound && EvaluateVariant(variant))
winnerFound = true;
}
// 若无变体胜出,提示将回退到本序列默认台词
if (!winnerFound)
{
var fallback = new Label("↳ 无变体满足,将使用本序列默认台词(无变体覆盖)");
fallback.style.fontSize = 11;
fallback.style.opacity = 0.6f;
fallback.style.marginTop = 4;
_resultContainer.Add(fallback);
}
}
private VisualElement BuildVariantRow(int index, DialogueSequenceSO.ConditionalVariant variant, bool higherWon)
{
bool condMet = EvaluateVariant(variant);
bool isWinner = condMet && !higherWon;
var card = new VisualElement();
card.style.borderLeftWidth = 3;
card.style.paddingLeft = 8;
card.style.paddingRight = 8;
card.style.paddingTop = 5;
card.style.paddingBottom = 5;
card.style.marginBottom = 4;
card.style.backgroundColor = new StyleColor(new Color(0.18f, 0.18f, 0.18f, 1f));
Color borderColor;
string statusText;
Color statusColor;
if (isWinner)
{
borderColor = ColWin;
statusText = "✓ 胜出";
statusColor = ColWin;
}
else if (condMet)
{
borderColor = ColOverride;
statusText = "⏩ 被更高优先级覆盖";
statusColor = ColOverride;
}
else
{
borderColor = ColFail;
statusText = "✗ 条件不满足";
statusColor = ColFail;
}
card.style.borderLeftColor = new StyleColor(borderColor);
// 标题行
var titleRow = new VisualElement();
titleRow.style.flexDirection = FlexDirection.Row;
titleRow.style.alignItems = Align.Center;
titleRow.style.marginBottom = 3;
var idxLabel = new Label($"变体 {index}");
idxLabel.style.fontSize = 11;
idxLabel.style.flexGrow = 1;
idxLabel.style.unityFontStyleAndWeight = isWinner ? FontStyle.Bold : FontStyle.Normal;
titleRow.Add(idxLabel);
var seqName = new Label(variant.sequence != null ? variant.sequence.name : "(未设置序列)");
seqName.style.fontSize = 10;
seqName.style.opacity = 0.6f;
seqName.style.width = 160;
titleRow.Add(seqName);
var statusLabel = new Label(statusText);
statusLabel.style.fontSize = 10;
statusLabel.style.color = new StyleColor(statusColor);
statusLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
titleRow.Add(statusLabel);
card.Add(titleRow);
// 逻辑类型
var logicLabel = new Label($"逻辑:{variant.logic}");
logicLabel.style.fontSize = 10;
logicLabel.style.opacity = 0.5f;
card.Add(logicLabel);
// 条件详情
if (variant.requiredFlags != null && variant.requiredFlags.Length > 0)
{
foreach (var flag in variant.requiredFlags)
{
if (string.IsNullOrEmpty(flag)) continue;
bool flagOn = _enabledFlags.Contains(flag);
var flagRow = new VisualElement();
flagRow.style.flexDirection = FlexDirection.Row;
flagRow.style.alignItems = Align.Center;
flagRow.style.marginTop = 1;
var icon = new Label(flagOn ? "✓" : "✗");
icon.style.fontSize = 10;
icon.style.color = new StyleColor(flagOn ? ColWin : ColBlocked);
icon.style.width = 16;
flagRow.Add(icon);
var flagLabel = new Label(flag);
flagLabel.style.fontSize = 10;
flagRow.Add(flagLabel);
card.Add(flagRow);
}
}
else
{
var noFlags = new Label("(无 requiredFlags — 无条件激活)");
noFlags.style.fontSize = 10;
noFlags.style.opacity = 0.5f;
card.Add(noFlags);
}
return card;
}
private bool EvaluateVariant(DialogueSequenceSO.ConditionalVariant variant)
{
// 使用 DialogueSequenceSO.CheckVariant 统一变体求值逻辑,避免重复实现
return _target != null && _target.CheckVariant(variant, _mockReader);
}
/// <summary>将 _enabledFlags 包装为 IWorldStateReader供 CheckVariant 调用。</summary>
private MockFlagReader _mockReader;
private sealed class MockFlagReader : BaseGames.Core.IWorldStateReader
{
private readonly System.Collections.Generic.HashSet<string> _flags;
public MockFlagReader(System.Collections.Generic.HashSet<string> flags) => _flags = flags;
public bool HasFlag(string key) => _flags.Contains(key);
}
// ── 辅助 ─────────────────────────────────────────────────────────────
private static VisualElement MakeDivider()
{
var d = new VisualElement();
d.style.height = 1;
d.style.backgroundColor = new StyleColor(new Color(0.35f, 0.35f, 0.35f, 0.5f));
d.style.marginTop = 6;
d.style.marginBottom = 6;
return d;
}
}
}

View File

@@ -63,7 +63,8 @@ namespace BaseGames.Editor.Dialogue
if (registry == null)
{
EditorGUILayout.HelpBox("未指定 WorldStateRegistry无法预览激活状态。\n请在 Inspector 中设置 World State 字段。", MessageType.Warning);
EditorGUILayout.HelpBox("未指定 WorldStateRegistry无法预览激活状态。\n" +
"可在 Inspector 中设置 World State 字段,或确保已通过 ServiceLocator 注册全局 IWorldStateReader。", MessageType.Warning);
DrawVersionLabelsOnly(versionsProp);
return;
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8217e62b4f33e3547895b6884c06bbea
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,6 +1,7 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using BaseGames.Core;
using BaseGames.Dialogue;
using BaseGames.EventChain;
using BaseGames.Editor;
@@ -35,6 +36,15 @@ namespace BaseGames.Editor.Dialogue
if (GUI.Button(btnRect, EditorGUIUtility.IconContent("d_icon dropdown"), EditorStyles.iconButton))
{
var flags = WorldStateFlagCollector.CollectKnownFlags();
var registry = BaseGames.Core.WorldFlagRegistrySO.EditorInstance;
// 构建注册表 id→entry 快速查找,用于在菜单项中显示分组和描述
var registryMap = new System.Collections.Generic.Dictionary<string, BaseGames.Core.FlagEntry>(
System.StringComparer.Ordinal);
if (registry?.flags != null)
foreach (var e in registry.flags)
if (e != null && !string.IsNullOrEmpty(e.id))
registryMap[e.id] = e;
var menu = new GenericMenu();
var current = property.stringValue;
var propPath = property.propertyPath;
@@ -43,8 +53,12 @@ namespace BaseGames.Editor.Dialogue
foreach (var flag in flags)
{
var captured = flag;
// 显示格式:分组/ID (分组来自注册表;无注册表条目则仅显示 ID
string menuPath = registryMap.TryGetValue(flag, out var entry) && !string.IsNullOrEmpty(entry.group)
? $"{entry.group}/{flag}"
: flag;
menu.AddItem(
new GUIContent(captured),
new GUIContent(menuPath),
current == captured,
() =>
{
@@ -62,6 +76,8 @@ namespace BaseGames.Editor.Dialogue
menu.AddSeparator(string.Empty);
menu.AddItem(new GUIContent("刷新列表"), false, WorldStateFlagCollector.Invalidate);
if (registry == null)
menu.AddDisabledItem(new GUIContent("⚠ 未找到 WorldFlagRegistry.asset可在 BaseGames 菜单创建)"));
menu.ShowAsContext();
}
@@ -139,6 +155,12 @@ namespace BaseGames.Editor.Dialogue
private static void CollectSoFlags(SortedSet<string> found)
{
// 优先加入注册表中的"官方"标志(排在下拉前列)
var registry = BaseGames.Core.WorldFlagRegistrySO.EditorInstance;
if (registry?.flags != null)
foreach (var entry in registry.flags)
if (!string.IsNullOrWhiteSpace(entry?.id)) found.Add(entry.id.Trim());
foreach (var a in AssetOperations.FindAll<SetFlagAction>())
if (!string.IsNullOrWhiteSpace(a.flagId)) found.Add(a.flagId.Trim());

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 787ab8ef75ae1cf439b9f7ee6bf21692
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -37,6 +37,9 @@ namespace BaseGames.Editor
private IDataModule _activeModule;
private VisualElement _navSidebar;
// NavBar 搜索:按 DisplayName 过滤可见模块
private string _navFilter = "";
private readonly Dictionary<string, Button> _navButtons = new();
// 缓存:列表区和详情区引用(由 TwoPaneSplitView 子节点提供)
private VisualElement _listWrapper;
@@ -70,16 +73,31 @@ namespace BaseGames.Editor
private void RegisterModules()
{
_modules.Clear();
_modules.Add(new WeaponModule());
_modules.Add(new SkillModule());
_modules.Add(new EnemyModule());
_modules.Add(new FormModule());
_modules.Add(new BossSkillModule());
_modules.Add(new CharmModule());
_modules.Add(new StreamingModule());
_modules.Add(new DialogueModule());
_modules.Add(new QuestModule());
_modules.Add(new ActorModule());
// 自动发现所有实现 IDataModule 的非抽象类型(排除接口/抽象类本身)
// TypeCache 仅在 UnityEditor 中可用,零运行时开销
var moduleTypes = UnityEditor.TypeCache.GetTypesDerivedFrom<IDataModule>();
var instances = new List<IDataModule>(moduleTypes.Count);
foreach (var t in moduleTypes)
{
if (t.IsAbstract || t.IsInterface) continue;
try { instances.Add((IDataModule)Activator.CreateInstance(t)); }
catch (Exception ex)
{
Debug.LogWarning($"[DataHubWindow] 无法实例化模块 {t.Name}: {ex.Message}");
}
}
// 按 DisplayOrder 升序排列(若模块实现了 IDataModuleOrdered 则使用其值,否则默认 0
instances.Sort((a, b) =>
{
int oa = a is IDataModuleOrdered ao ? ao.DisplayOrder : 0;
int ob = b is IDataModuleOrdered bo ? bo.DisplayOrder : 0;
int c = oa.CompareTo(ob);
return c != 0 ? c : string.Compare(a.DisplayName, b.DisplayName, StringComparison.OrdinalIgnoreCase);
});
_modules.AddRange(instances);
}
// ── 布局 ─────────────────────────────────────────────────────────────
@@ -136,13 +154,31 @@ namespace BaseGames.Editor
title.style.fontSize = 10;
title.style.opacity = 0.5f;
title.style.paddingLeft = 10;
title.style.marginBottom = 6;
title.style.marginBottom = 4;
title.style.unityFontStyleAndWeight = FontStyle.Bold;
sidebar.Add(title);
// 搜索框
var searchField = new TextField();
searchField.style.marginLeft = 6;
searchField.style.marginRight = 6;
searchField.style.marginBottom = 6;
searchField.tooltip = "按模块名称过滤";
// 自定义占位符效果
if (string.IsNullOrEmpty(searchField.value))
searchField.value = "";
searchField.RegisterValueChangedCallback(evt =>
{
_navFilter = evt.newValue ?? "";
ApplyNavFilter();
});
sidebar.Add(searchField);
_navButtons.Clear();
foreach (var module in _modules)
{
var btn = BuildNavItem(module);
_navButtons[module.ModuleId] = btn;
sidebar.Add(btn);
}
@@ -154,6 +190,18 @@ namespace BaseGames.Editor
return sidebar;
}
private void ApplyNavFilter()
{
foreach (var module in _modules)
{
if (!_navButtons.TryGetValue(module.ModuleId, out var btn)) continue;
bool visible = string.IsNullOrEmpty(_navFilter) ||
module.DisplayName.IndexOf(_navFilter, System.StringComparison.OrdinalIgnoreCase) >= 0 ||
module.ModuleId.IndexOf(_navFilter, System.StringComparison.OrdinalIgnoreCase) >= 0;
btn.style.display = visible ? DisplayStyle.Flex : DisplayStyle.None;
}
}
private Button BuildNavItem(IDataModule module)
{
var btn = new Button(() => ActivateModule(module));

View File

@@ -25,4 +25,17 @@ namespace BaseGames.Editor
/// <summary>切换到本模块时调用,可用于刷新数据。</summary>
void OnActivated();
}
/// <summary>
/// 可选排序接口。DataHubWindow 自动发现模块时按 <see cref="DisplayOrder"/> 升序排列。
/// 未实现此接口的模块默认顺序为 0再按 DisplayName 字母序排列。
/// </summary>
public interface IDataModuleOrdered
{
/// <summary>
/// 导航侧边栏排列顺序。数值越小越靠前。
/// 建议使用 10, 20, 30… 间隔,便于插入新模块。
/// </summary>
int DisplayOrder { get; }
}
}

View File

@@ -11,7 +11,7 @@ namespace BaseGames.Editor.Modules
/// DataHub 对话角色模块 —— 管理 DialogueActorSO 资产。
/// 统一查看、创建、重命名、删除 NPC/玩家角色定义(头像、名称 Key、强调色
/// </summary>
public class ActorModule : IDataModule
public class ActorModule : IDataModule, IDataModuleOrdered
{
private const string Folder = "Assets/_Game/Data/Dialogue/Actors";
private const string Prefix = "Actor_";
@@ -19,6 +19,7 @@ namespace BaseGames.Editor.Modules
public string ModuleId => "actor";
public string DisplayName => "角色";
public string IconName => "d_Prefab Icon";
public int DisplayOrder => 80;
private SoListPane<DialogueActorSO> _listPane;
private DetailHeader _header;
@@ -76,7 +77,15 @@ namespace BaseGames.Editor.Modules
var card = SkillModule.MakeCard();
SkillModule.AddChip(card, "ID", string.IsNullOrEmpty(a.actorId) ? "(未设置)" : a.actorId);
SkillModule.AddChip(card, "名称 Key", string.IsNullOrEmpty(a.nameKey) ? "(未设置)" : a.nameKey);
// 名称:优先显示本地化实际文本,回退到 key 本身
string nameDisplay = string.IsNullOrEmpty(a.nameKey)
? "(未设置)"
: (BaseGames.Localization.LocalizationManager.GetEditorPreview(a.nameKey, "Dialogue") ?? a.nameKey);
SkillModule.AddChip(card, "名称", nameDisplay);
if (!string.IsNullOrEmpty(a.nameKey))
SkillModule.AddChip(card, "名称 Key", a.nameKey);
if (a.isPlayer)
SkillModule.AddChip(card, "类型", "玩家");

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1432dc664312c954e9b4adb0cbb6f25e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -10,7 +10,7 @@ namespace BaseGames.Editor.Modules
/// <summary>
/// DataHub Boss技能模块 —— Tab 切换管理 BossSkillSO 和 SkillSequenceSO。
/// </summary>
public class BossSkillModule : IDataModule
public class BossSkillModule : IDataModule, IDataModuleOrdered
{
private const string SkillFolder = "Assets/_Game/Data/Boss/Skills";
private const string SeqFolder = "Assets/_Game/Data/Boss/Sequences";
@@ -18,6 +18,7 @@ namespace BaseGames.Editor.Modules
public string ModuleId => "boss";
public string DisplayName => "Boss技能";
public string IconName => null;
public int DisplayOrder => 50;
private int _activeTab = 0;

View File

@@ -10,7 +10,7 @@ namespace BaseGames.Editor.Modules
/// <summary>
/// DataHub 护符模块 —— Tab 切换管理 CharmCatalogSO目录和 CharmSO护符资产。
/// </summary>
public class CharmModule : IDataModule
public class CharmModule : IDataModule, IDataModuleOrdered
{
private const string CharmFolder = "Assets/_Game/Data/Progression/Charms";
private const string CatalogPrefix = "CHM_Catalog";
@@ -19,6 +19,7 @@ namespace BaseGames.Editor.Modules
public string ModuleId => "charm";
public string DisplayName => "护符";
public string IconName => null;
public int DisplayOrder => 60;
private int _activeTab = 0; // 0 = 目录, 1 = 护符

View File

@@ -4,13 +4,15 @@ using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using BaseGames.Dialogue;
using BaseGames.Editor.Dialogue;
using BaseGames.Editor.Shared;
namespace BaseGames.Editor.Modules
{
/// <summary>
/// DataHub 对话序列模块 —— 管理 DialogueSequenceSO 资产。
/// </summary>
public class DialogueModule : IDataModule
public class DialogueModule : IDataModule, IDataModuleOrdered
{
private const string Folder = "Assets/_Game/Data/Dialogue";
private const string Prefix = "DLG_";
@@ -18,6 +20,7 @@ namespace BaseGames.Editor.Modules
public string ModuleId => "dialogue";
public string DisplayName => "对话";
public string IconName => "d_UnityEditor.ConsoleWindow";
public int DisplayOrder => 100;
private SoListPane<DialogueSequenceSO> _listPane;
private DetailHeader _header;
@@ -29,9 +32,20 @@ namespace BaseGames.Editor.Modules
Folder, Prefix,
s =>
{
int v = s.variants != null ? s.variants.Length : 0;
return v > 0 ? $"{v}变体" : null;
if (s.variants == null || s.variants.Length == 0) return null;
int v = s.variants.Length;
// 检测无条件变体遮蔽(非末尾的无条件变体会让后续变体永不命中)
bool hasShadow = false;
for (int i = 0; i < s.variants.Length - 1; i++)
{
var vv = s.variants[i];
if (vv.sequence != null && (vv.requiredFlags == null || vv.requiredFlags.Length == 0))
{ hasShadow = true; break; }
}
return hasShadow ? $"{v}变体 ⚠" : $"{v}变体";
});
// 扩展搜索sequenceId
_listPane.GetExtraSearchText = d => d.sequenceId;
}
public void BuildListPane(VisualElement container, Action<UnityEngine.Object> onSelected)
@@ -41,6 +55,52 @@ namespace BaseGames.Editor.Modules
_selected = sel;
onSelected?.Invoke(sel);
};
// ── 快速过滤标签行 ────────────────────────────────────────────
var filterRow = new VisualElement();
filterRow.style.flexDirection = FlexDirection.Row;
filterRow.style.flexWrap = Wrap.Wrap;
filterRow.style.paddingLeft = 6;
filterRow.style.paddingRight = 6;
filterRow.style.paddingBottom = 3;
container.Add(filterRow);
bool filterVariants = false, filterBranches = false, filterNoVoice = false;
void RebuildFilter()
{
if (!filterVariants && !filterBranches && !filterNoVoice)
{
_listPane.ExtraFilter = null;
return;
}
_listPane.ExtraFilter = s =>
{
if (filterVariants && (s.variants == null || s.variants.Length == 0)) return false;
if (filterBranches)
{
bool hasBranch = false;
if (s.lines != null)
foreach (var l in s.lines)
if (l.choices != null && l.choices.Length > 0) { hasBranch = true; break; }
if (!hasBranch) return false;
}
if (filterNoVoice)
{
bool hasVoice = false;
if (s.lines != null)
foreach (var l in s.lines)
if (l.voiceClip != null) { hasVoice = true; break; }
if (hasVoice) return false;
}
return true;
};
}
filterRow.Add(QuestModule.MakeFilterChip("有变体", v => { filterVariants = v; RebuildFilter(); }));
filterRow.Add(QuestModule.MakeFilterChip("有分支", v => { filterBranches = v; RebuildFilter(); }));
filterRow.Add(QuestModule.MakeFilterChip("无语音", v => { filterNoVoice = v; RebuildFilter(); }));
container.Add(_listPane);
_listPane.Refresh();
}
@@ -90,8 +150,11 @@ namespace BaseGames.Editor.Modules
return card;
}
private static VisualElement BuildLinesPreview(DialogueSequenceSO s)
private VisualElement BuildLinesPreview(DialogueSequenceSO s)
{
var so = new SerializedObject(s);
var linesProp = so.FindProperty("lines");
var section = new VisualElement();
section.style.paddingLeft = 12;
section.style.paddingRight = 12;
@@ -114,14 +177,14 @@ namespace BaseGames.Editor.Modules
return section;
}
int preview = Mathf.Min(5, s.lines.Length);
for (int i = 0; i < preview; i++)
int previewCount = Mathf.Min(5, s.lines.Length);
for (int i = 0; i < previewCount; i++)
{
var line = s.lines[i];
var row = new VisualElement();
row.style.flexDirection = FlexDirection.Row;
row.style.alignItems = Align.Center;
row.style.marginBottom = 3;
row.style.marginBottom = 2;
// 头像图标actor 优先,回退到直接字段)
var portrait = line.ResolvedPortrait;
@@ -152,36 +215,126 @@ namespace BaseGames.Editor.Modules
}
}
// 说话人actor 优先,回退到直接字段)
// 说话人actor 优先,回退到直接字段;尝试解析本地化实际文本
string speakerKey = line.ResolvedNameKey;
if (!string.IsNullOrEmpty(speakerKey))
{
var spk = new Label(speakerKey + ":");
var speakerResolved = BaseGames.Localization.LocalizationManager.GetEditorPreview(speakerKey, "Dialogue");
bool speakerMissing = speakerResolved == null;
string speakerText = speakerMissing ? speakerKey : speakerResolved;
var spk = new Label(speakerText + ":");
spk.style.fontSize = 11;
spk.style.opacity = 0.55f;
spk.style.unityFontStyleAndWeight = FontStyle.Bold;
spk.style.marginRight = 4;
spk.style.flexShrink = 0;
var accent = line.ResolvedAccentColor;
if (speakerMissing)
{
// 说话人 Key 缺少本地化 → 橙色警告
spk.style.color = new StyleColor(new Color(1f, 0.6f, 0.1f));
spk.style.opacity = 1.0f;
}
else if (accent != Color.white)
{
spk.style.color = new StyleColor(accent);
spk.style.opacity = 1.0f;
}
else
{
spk.style.opacity = 0.55f;
}
row.Add(spk);
}
// 文本 key尝试显示本地化实际内容回退到 key 本身
string rawText = string.IsNullOrEmpty(line.textKey) ? "(空)" : line.textKey;
string preview = string.IsNullOrEmpty(line.textKey)
? "(空)"
: (BaseGames.Localization.LocalizationManager.GetEditorPreview(line.textKey, "Dialogue") ?? rawText);
if (preview.Length > 48) preview = preview[..48] + "…";
var lbl = new Label(preview);
// 文本本地化预览Key 有值但无本地化内容时橙色 ⚠ 警告
string textPreview;
bool textL10nMissing = false;
if (string.IsNullOrEmpty(line.textKey))
{
textPreview = "(空)";
}
else
{
var resolved = BaseGames.Localization.LocalizationManager.GetEditorPreview(line.textKey, "Dialogue");
if (resolved != null)
{
textPreview = resolved;
}
else
{
textPreview = line.textKey + " ⚠";
textL10nMissing = true;
}
}
if (textPreview.Length > 48) textPreview = textPreview[..48] + "…";
var lbl = new Label(textPreview);
lbl.style.fontSize = 11;
lbl.style.overflow = Overflow.Hidden;
lbl.style.flexGrow = 1;
if (textL10nMissing)
lbl.style.color = new StyleColor(new Color(1f, 0.6f, 0.1f));
row.Add(lbl);
// 选项分支徽章(有 choices 时显示"→N选"
if (line.choices != null && line.choices.Length > 0)
{
var choiceBadge = new Label($"→{line.choices.Length}选");
choiceBadge.style.fontSize = 9;
choiceBadge.style.color = new StyleColor(new Color(0.3f, 0.8f, 1f));
choiceBadge.style.marginLeft = 4;
choiceBadge.style.flexShrink = 0;
row.Add(choiceBadge);
}
// ▾ 内联编辑按钮
var editBtn = new Button { text = "▾" };
editBtn.style.fontSize = 9;
editBtn.style.marginLeft = 4;
editBtn.style.paddingLeft = 3;
editBtn.style.paddingRight = 3;
editBtn.style.height = 16;
row.Add(editBtn);
// 内联编辑区域(默认隐藏,点击 ▾ 展开)
int capturedIdx = i;
var editRow = new VisualElement();
editRow.style.display = DisplayStyle.None;
editRow.style.paddingLeft = 26;
editRow.style.paddingRight = 8;
editRow.style.marginBottom = 4;
if (linesProp != null)
{
var lineProp = linesProp.GetArrayElementAtIndex(capturedIdx);
var textKeyProp = lineProp?.FindPropertyRelative("textKey");
if (textKeyProp != null)
{
var tf = new TextField("文本 Key") { value = textKeyProp.stringValue };
tf.style.fontSize = 10;
tf.RegisterValueChangedCallback(evt =>
{
so.Update();
textKeyProp.stringValue = evt.newValue;
so.ApplyModifiedProperties();
});
editRow.Add(tf);
}
}
editBtn.clicked += () =>
{
bool open = editRow.style.display == DisplayStyle.None;
editRow.style.display = open ? DisplayStyle.Flex : DisplayStyle.None;
editBtn.text = open ? "▴" : "▾";
};
section.Add(row);
section.Add(editRow);
}
if (s.lines.Length > preview)
if (s.lines.Length > previewCount)
{
var more = new Label($"… 还有 {s.lines.Length - preview} 行");
var more = new Label($"… 还有 {s.lines.Length - previewCount} 行");
more.style.opacity = 0.4f;
more.style.fontSize = 10;
section.Add(more);
@@ -202,29 +355,207 @@ namespace BaseGames.Editor.Modules
title.style.unityFontStyleAndWeight = FontStyle.Bold;
card.Add(title);
foreach (var v in s.variants)
for (int i = 0; i < s.variants.Length; i++)
{
var v = s.variants[i];
var row = new VisualElement();
row.style.flexDirection = FlexDirection.Row;
row.style.marginBottom = 2;
string flags = v.requiredFlags != null && v.requiredFlags.Length > 0
? string.Join(", ", v.requiredFlags)
: "(无条件)";
SkillModule.AddChip(row, "条件", flags);
SkillModule.AddChip(row, "替换序列", v.sequence != null ? v.sequence.name : "(未设置)");
bool isUnconditional = v.requiredFlags == null || v.requiredFlags.Length == 0;
bool isShadowing = isUnconditional && v.sequence != null && i < s.variants.Length - 1;
// 条件徽章显示逻辑模式And/Or和标志列表
string conditionText;
if (isUnconditional)
{
conditionText = isShadowing ? "⚠ (无条件)" : "(无条件)";
}
else
{
string logicPrefix = v.requiredFlags.Length > 1
? $"[{(v.logic == BaseGames.Core.WorldStateFlagLogic.Or ? "OR" : "AND")}] "
: "";
conditionText = logicPrefix + string.Join(", ", v.requiredFlags);
}
SkillModule.AddChip(row, "条件", conditionText);
// 替换序列徽章
string seqName = v.sequence != null ? v.sequence.name : "(未设置)";
int seqLines = v.sequence != null && v.sequence.lines != null ? v.sequence.lines.Length : 0;
string seqLabel = v.sequence != null ? $"{seqName}{seqLines}行)" : seqName;
SkillModule.AddChip(row, "替换序列", seqLabel);
card.Add(row);
// 遮蔽警告行
if (isShadowing)
{
int remaining = s.variants.Length - 1 - i;
var warn = new Label($" ↑ 此变体无条件,其后 {remaining} 个变体永不生效。请移至末尾或添加条件。");
warn.style.fontSize = 9;
warn.style.color = new StyleColor(new Color(1f, 0.6f, 0.1f));
warn.style.marginBottom = 2;
card.Add(warn);
}
}
return card;
}
private VisualElement BuildActionBar(DialogueSequenceSO s)
{
return SkillModule.BuildStandardActionBar(
var bar = SkillModule.BuildStandardActionBar(
s, Folder, Prefix,
onCreated: c => _listPane.Refresh(c),
onCloned: c => _listPane.Refresh(c),
onDeleted: () => _listPane.Refresh(null));
onDeleted: () => _listPane.Refresh(null),
wizardCreate: cb => AssetCreationWizard.Show<DialogueSequenceSO>(
Folder, Prefix,
(d, id) =>
{
d.sequenceId = id;
EditorUtility.SetDirty(d);
AssetDatabase.SaveAssets();
cb(d);
}));
new Button(ValidateAllSequences) { text = "批量验证" }.AlsoAddTo(bar);
if (s.variants != null && s.variants.Length > 0)
{
var capturedS = s;
new Button(() => DialogueVariantPreviewWindow.OpenWith(capturedS))
{ text = "预览变体" }.AlsoAddTo(bar);
}
return bar;
}
// ── 批量验证 ─────────────────────────────────────────────────────────
/// <summary>
/// 遍历所有 DialogueSequenceSO检查
/// 1. sequenceId 为空
/// 2. sequenceId 重复
/// 3. 每行 textKey 是否在本地化表中存在
/// 4. 每行 speakerNameKey无 actor 时)是否在本地化表中存在
/// 5. 每个选项 textKey 是否在本地化表中存在
/// 结果显示在 QuestValidationResultWindow 中,每项问题附"选中"按钮可一键定位资产。
/// </summary>
private static void ValidateAllSequences()
{
var allSeqs = AssetOperations.FindAll<DialogueSequenceSO>();
var issues = new System.Collections.Generic.List<QuestValidationResultWindow.Issue>();
int errorCount = 0, warnCount = 0;
// 预构建本地化缓存(整个验证过程只查询一次,避免大批量序列时重复读取本地化表)
var locCache = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.Ordinal);
string GetLoc(string key)
{
if (locCache.TryGetValue(key, out var v)) return v;
v = BaseGames.Localization.LocalizationManager.GetEditorPreview(key, "Dialogue");
locCache[key] = v;
return v;
}
void AddError(string msg, UnityEngine.Object asset = null)
{
issues.Add(new QuestValidationResultWindow.Issue { message = msg, isError = true, asset = asset });
errorCount++;
}
void AddWarn(string msg, UnityEngine.Object asset = null)
{
issues.Add(new QuestValidationResultWindow.Issue { message = msg, isError = false, asset = asset });
warnCount++;
}
// 1 & 2空 / 重复 sequenceId
var idMap = new System.Collections.Generic.Dictionary<string, DialogueSequenceSO>(System.StringComparer.Ordinal);
var keyFormatRegex = new System.Text.RegularExpressions.Regex(@"^[\w\-\.]+$");
foreach (var seq in allSeqs)
{
if (string.IsNullOrWhiteSpace(seq.sequenceId))
{
AddError($"{seq.name}: sequenceId 为空。", seq);
continue;
}
if (idMap.TryGetValue(seq.sequenceId, out var existing))
AddError($"重复 sequenceId \"{seq.sequenceId}\"{seq.name} 与 {existing.name}", seq);
else
idMap[seq.sequenceId] = seq;
// 2b. sequenceId 格式异常
if (!keyFormatRegex.IsMatch(seq.sequenceId))
AddWarn($"{seq.name}: sequenceId \"{seq.sequenceId}\" 含有空格或非法字符建议只使用字母、数字、_、-、.。", seq);
}
// 3-5本地化 Key 存在性 + 格式检查
foreach (var seq in allSeqs)
{
if (seq.lines == null) continue;
for (int i = 0; i < seq.lines.Length; i++)
{
var line = seq.lines[i];
string lineDesc = $"{seq.name} 行[{i}]";
// 文本 Key
if (string.IsNullOrEmpty(line.textKey))
{
AddWarn($"{lineDesc}: textKey 为空,运行时显示空文本。", seq);
}
else
{
if (GetLoc(line.textKey) == null)
AddWarn($"{lineDesc}: textKey \"{line.textKey}\" 在本地化表中不存在。", seq);
if (!keyFormatRegex.IsMatch(line.textKey))
AddWarn($"{lineDesc}: textKey \"{line.textKey}\" 含有空格或非法字符。", seq);
}
// 说话人 Key无 actor 时检查直接字段)
if (line.actor == null && !string.IsNullOrEmpty(line.speakerNameKey))
{
if (GetLoc(line.speakerNameKey) == null)
AddWarn($"{lineDesc}: speakerNameKey \"{line.speakerNameKey}\" 在本地化表中不存在。", seq);
if (!keyFormatRegex.IsMatch(line.speakerNameKey))
AddWarn($"{lineDesc}: speakerNameKey \"{line.speakerNameKey}\" 含有空格或非法字符。", seq);
}
// 选项 Key
if (line.choices != null)
{
for (int j = 0; j < line.choices.Length; j++)
{
var choice = line.choices[j];
if (string.IsNullOrEmpty(choice.textKey))
{
AddWarn($"{lineDesc} 选项[{j}]: textKey 为空。", seq);
}
else
{
if (GetLoc(choice.textKey) == null)
AddWarn($"{lineDesc} 选项[{j}]: textKey \"{choice.textKey}\" 在本地化表中不存在。", seq);
if (!keyFormatRegex.IsMatch(choice.textKey))
AddWarn($"{lineDesc} 选项[{j}]: textKey \"{choice.textKey}\" 含有空格或非法字符。", seq);
}
}
}
}
}
// 6. variants[i].sequence 为 null变体存在但序列引用为空
foreach (var seq in allSeqs)
{
if (seq.variants == null) continue;
for (int vi = 0; vi < seq.variants.Length; vi++)
{
if (seq.variants[vi].sequence == null)
AddWarn($"{seq.name}: variants[{vi}].sequence 为 null满足条件时会回退默认序列可能是未完成配置。", seq);
}
}
Debug.Log($"[DialogueModule] 验证完成:{allSeqs.Count} 个序列,{errorCount} 个错误,{warnCount} 个警告。");
QuestValidationResultWindow.Show(issues, errorCount, warnCount, allSeqs.Count, "对话批量验证结果", "序列");
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 76733bfe043064b4a980287067333483
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -10,7 +10,7 @@ namespace BaseGames.Editor.Modules
/// <summary>
/// DataHub 敌人模块 —— Tab 切换管理 EnemyStatsSO 和 LootTableSO。
/// </summary>
public class EnemyModule : IDataModule
public class EnemyModule : IDataModule, IDataModuleOrdered
{
private const string StatsFolder = "Assets/_Game/Data/Enemies/Stats";
private const string LootFolder = "Assets/_Game/Data/Enemies/Loot";
@@ -18,6 +18,7 @@ namespace BaseGames.Editor.Modules
public string ModuleId => "enemy";
public string DisplayName => "敌人";
public string IconName => null;
public int DisplayOrder => 30;
private int _activeTab = 0; // 0=Stats, 1=Loot

View File

@@ -0,0 +1,526 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using BaseGames.EventChain;
using BaseGames.Editor.Shared;
namespace BaseGames.Editor.Modules
{
/// <summary>
/// DataHub 事件链模块 —— 管理 EventChainSO 资产。
/// 支持浏览、创建、删除、预览条件/动作列表,以及批量验证。
/// </summary>
public class EventChainModule : IDataModule, IDataModuleOrdered
{
private const string Folder = "Assets/_Game/Data/EventChains";
private const string Prefix = "Chain_";
public string ModuleId => "eventchain";
public string DisplayName => "事件链";
public string IconName => "d_Animation.Play";
public int DisplayOrder => 120;
private SoListPane<EventChainSO> _listPane;
private DetailHeader _header;
private EventChainSO _selected;
// ── IDataModule ───────────────────────────────────────────────────────
public void Initialize()
{
_listPane = new SoListPane<EventChainSO>(
Folder, Prefix,
c => c.repeatable ? "可重复" : null);
// 扩展搜索chainId
_listPane.GetExtraSearchText = c => c.chainId;
}
public void BuildListPane(VisualElement container, Action<UnityEngine.Object> onSelected)
{
_listPane.SelectionChanged = sel =>
{
_selected = sel;
onSelected?.Invoke(sel);
};
// 快速过滤标签行
var filterRow = new VisualElement();
filterRow.style.flexDirection = FlexDirection.Row;
filterRow.style.flexWrap = Wrap.Wrap;
filterRow.style.paddingLeft = 6;
filterRow.style.paddingRight = 6;
filterRow.style.paddingBottom = 3;
container.Add(filterRow);
bool filterRepeatable = false, filterNoCondition = false, filterNoAction = false;
void RebuildFilter()
{
if (!filterRepeatable && !filterNoCondition && !filterNoAction)
{
_listPane.ExtraFilter = null;
return;
}
_listPane.ExtraFilter = c =>
{
if (filterRepeatable && !c.repeatable) return false;
if (filterNoCondition && c.conditions != null && c.conditions.Length > 0) return false;
if (filterNoAction && c.actions != null && c.actions.Length > 0) return false;
return true;
};
}
filterRow.Add(QuestModule.MakeFilterChip("可重复", v => { filterRepeatable = v; RebuildFilter(); }));
filterRow.Add(QuestModule.MakeFilterChip("无条件", v => { filterNoCondition = v; RebuildFilter(); }));
filterRow.Add(QuestModule.MakeFilterChip("无动作", v => { filterNoAction = v; RebuildFilter(); }));
container.Add(_listPane);
_listPane.Refresh();
}
public void BuildDetailPane(VisualElement container, UnityEngine.Object selected)
{
_selected = selected as EventChainSO;
_header = new DetailHeader();
_header.SetAsset(_selected);
_header.RenameRequested += OnRenameRequested;
container.Add(_header);
if (_selected == null) return;
container.Add(BuildInfoCard(_selected));
container.Add(BuildConditionsList(_selected));
container.Add(BuildActionsList(_selected));
container.Add(BuildActionBar(_selected));
container.Add(SkillModule.MakeDivider());
container.Add(new UnityEditor.UIElements.InspectorElement(_selected));
}
public void OnActivated() => _listPane?.Refresh();
// ── 内部 ──────────────────────────────────────────────────────────────
private void OnRenameRequested(string newName)
{
if (_selected == null) return;
var (ok, err) = AssetOperations.Rename(_selected, newName);
if (!ok) EditorUtility.DisplayDialog("重命名失败", err, "确定");
else { _header.SetAsset(_selected); _listPane.Invalidate(); }
}
private static VisualElement BuildInfoCard(EventChainSO c)
{
var card = SkillModule.MakeCard();
SkillModule.AddChip(card, "Chain ID",
string.IsNullOrEmpty(c.chainId) ? "(未设置)" : c.chainId);
SkillModule.AddChip(card, "可重复", c.repeatable ? "是" : "否");
if (c.actionDelay > 0f)
SkillModule.AddChip(card, "动作间隔", $"{c.actionDelay:F2}s");
int condCount = c.conditions?.Length ?? 0;
int actCount = c.actions?.Length ?? 0;
SkillModule.AddChip(card, "条件数量", condCount.ToString());
SkillModule.AddChip(card, "动作数量", actCount.ToString());
return card;
}
private static VisualElement BuildConditionsList(EventChainSO c)
{
var section = new VisualElement();
section.style.paddingLeft = 12;
section.style.paddingRight = 12;
section.style.paddingTop = 6;
section.style.paddingBottom = 4;
var title = new Label("触发条件");
title.style.unityFontStyleAndWeight = FontStyle.Bold;
title.style.fontSize = 11;
title.style.opacity = 0.8f;
title.style.marginBottom = 4;
section.Add(title);
bool hasGroups = c.conditionGroups != null && c.conditionGroups.Length > 0;
bool hasLegacy = c.conditions != null && c.conditions.Length > 0;
if (!hasGroups && !hasLegacy)
{
var empty = new Label("(无条件,链将立即在首次 EvaluateAll 时触发)");
empty.style.opacity = 0.5f;
empty.style.fontSize = 11;
section.Add(empty);
return section;
}
if (hasGroups)
{
// 新版 conditionGroups 展示
for (int g = 0; g < c.conditionGroups.Length; g++)
{
var group = c.conditionGroups[g];
// 组标题
var groupHeader = new VisualElement();
groupHeader.style.flexDirection = FlexDirection.Row;
groupHeader.style.alignItems = Align.Center;
groupHeader.style.marginBottom = 2;
groupHeader.style.marginTop = g > 0 ? 4 : 0;
var gLabel = new Label($"条件组 {g + 1}");
gLabel.style.fontSize = 11;
gLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
gLabel.style.flexGrow = 1;
groupHeader.Add(gLabel);
var logicBadge = new Label(group.logic == BaseGames.Core.WorldStateFlagLogic.Or ? "Or任一满足" : "And全部满足");
logicBadge.style.fontSize = 10;
logicBadge.style.opacity = 0.6f;
groupHeader.Add(logicBadge);
section.Add(groupHeader);
if (group.conditions == null || group.conditions.Length == 0)
{
var noCondLabel = new Label(" (空组 — 无条件即视为满足)");
noCondLabel.style.opacity = 0.45f;
noCondLabel.style.fontSize = 11;
section.Add(noCondLabel);
continue;
}
for (int i = 0; i < group.conditions.Length; i++)
section.Add(BuildConditionRow(i, group.conditions[i], indent: true));
}
}
else
{
// 旧版 conditions[](隐式 And
var legacyNote = new Label("(旧版条件列表,隐式 And 逻辑;建议迁移至 conditionGroups");
legacyNote.style.opacity = 0.45f;
legacyNote.style.fontSize = 10;
legacyNote.style.marginBottom = 2;
section.Add(legacyNote);
for (int i = 0; i < c.conditions.Length; i++)
section.Add(BuildConditionRow(i, c.conditions[i], indent: false));
}
// ── 运行时求值按钮(仅 Play Mode──────────────────────────────
if (Application.isPlaying)
{
section.Add(BuildRuntimeEvalPanel(c));
}
return section;
}
private static VisualElement BuildConditionRow(int index, ChainCondition cond, bool indent)
{
var row = new VisualElement();
row.style.flexDirection = FlexDirection.Row;
row.style.alignItems = Align.Center;
row.style.marginBottom = 2;
if (indent) row.style.paddingLeft = 12;
var idx = new Label($"{index + 1}.");
idx.style.width = 18;
idx.style.opacity = 0.5f;
idx.style.fontSize = 11;
row.Add(idx);
if (cond == null)
{
var warn = new Label("⚠ nullInspector 中有空槽,请检查)");
warn.style.color = new StyleColor(new Color(0.9f, 0.5f, 0.2f));
warn.style.fontSize = 11;
row.Add(warn);
}
else
{
// 运行时:直接显示 IsMet() 结果
if (Application.isPlaying)
{
bool met = cond.IsMet();
var statusIcon = new Label(met ? "✓" : "✗");
statusIcon.style.fontSize = 11;
statusIcon.style.width = 14;
statusIcon.style.color = new StyleColor(met
? new Color(0.2f, 0.75f, 0.35f)
: new Color(0.85f, 0.35f, 0.30f));
row.Add(statusIcon);
}
var typeName = new Label(cond.GetType().Name);
typeName.style.flexGrow = 1;
typeName.style.fontSize = 11;
row.Add(typeName);
var ping = new Button(() => { EditorGUIUtility.PingObject(cond); Selection.activeObject = cond; })
{ text = "定位" };
ping.style.fontSize = 10;
ping.style.height = 18;
row.Add(ping);
}
return row;
}
private static VisualElement BuildRuntimeEvalPanel(EventChainSO c)
{
var panel = new VisualElement();
panel.style.marginTop = 6;
panel.style.paddingTop = 4;
panel.style.paddingBottom = 4;
panel.style.paddingLeft = 8;
panel.style.paddingRight = 8;
panel.style.backgroundColor = new StyleColor(new Color(0.15f, 0.22f, 0.15f, 1f));
var header = new VisualElement();
header.style.flexDirection = FlexDirection.Row;
header.style.alignItems = Align.Center;
header.style.marginBottom = 2;
var title = new Label("▶ 运行时状态");
title.style.fontSize = 10;
title.style.opacity = 0.7f;
title.style.flexGrow = 1;
title.style.unityFontStyleAndWeight = FontStyle.Bold;
header.Add(title);
var resultLabel = new Label();
resultLabel.style.fontSize = 10;
void RefreshEval()
{
// 简单逐条 IsMet 求值用于显示(不触发实际执行)
bool hasGroups = c.conditionGroups != null && c.conditionGroups.Length > 0;
bool allPass = true;
if (hasGroups)
{
foreach (var g in c.conditionGroups)
{
if (g.conditions == null || g.conditions.Length == 0) continue;
bool groupPass = g.logic == BaseGames.Core.WorldStateFlagLogic.Or
? System.Array.Exists(g.conditions, x => x != null && x.IsMet())
: System.Array.TrueForAll(g.conditions, x => x == null || x.IsMet());
if (!groupPass) { allPass = false; break; }
}
}
else if (c.conditions != null)
{
allPass = System.Array.TrueForAll(c.conditions, x => x == null || x.IsMet());
}
resultLabel.text = allPass ? "✓ 当前满足触发条件" : "✗ 当前不满足触发条件";
resultLabel.style.color = new StyleColor(allPass
? new Color(0.2f, 0.75f, 0.35f)
: new Color(0.85f, 0.35f, 0.30f));
}
RefreshEval();
var refreshBtn = new Button(RefreshEval) { text = "刷新" };
refreshBtn.style.fontSize = 9;
refreshBtn.style.height = 16;
header.Add(refreshBtn);
panel.Add(header);
panel.Add(resultLabel);
return panel;
}
private static VisualElement BuildActionsList(EventChainSO c)
{
var section = new VisualElement();
section.style.paddingLeft = 12;
section.style.paddingRight = 12;
section.style.paddingTop = 6;
section.style.paddingBottom = 4;
var title = new Label("执行动作");
title.style.unityFontStyleAndWeight = FontStyle.Bold;
title.style.fontSize = 11;
title.style.opacity = 0.8f;
title.style.marginBottom = 4;
section.Add(title);
if (c.actions == null || c.actions.Length == 0)
{
var empty = new Label("(无动作,链触发后不执行任何操作)");
empty.style.opacity = 0.5f;
empty.style.fontSize = 11;
section.Add(empty);
return section;
}
for (int i = 0; i < c.actions.Length; i++)
{
var act = c.actions[i];
var row = new VisualElement();
row.style.flexDirection = FlexDirection.Row;
row.style.alignItems = Align.Center;
row.style.marginBottom = 2;
var idx = new Label($"{i + 1}.");
idx.style.width = 18;
idx.style.opacity = 0.5f;
idx.style.fontSize = 11;
row.Add(idx);
if (act == null)
{
var warn = new Label("⚠ nullInspector 中有空槽,请检查)");
warn.style.color = new StyleColor(new Color(0.9f, 0.5f, 0.2f));
warn.style.fontSize = 11;
row.Add(warn);
}
else
{
var typeName = new Label($"{act.GetType().Name} {act.name}");
typeName.style.flexGrow = 1;
typeName.style.fontSize = 11;
row.Add(typeName);
var ping = new Button(() => { EditorGUIUtility.PingObject(act); Selection.activeObject = act; })
{ text = "定位" };
ping.style.fontSize = 10;
ping.style.height = 18;
row.Add(ping);
}
section.Add(row);
}
return section;
}
private VisualElement BuildActionBar(EventChainSO c)
{
var bar = SkillModule.MakeActionBar();
new Button(() =>
{
AssetCreationWizard.Show<EventChainSO>(Folder, Prefix, (asset, id) =>
{
asset.chainId = id;
EditorUtility.SetDirty(asset);
AssetDatabase.SaveAssets();
_listPane.Refresh(asset);
});
}) { text = "创建" }.AlsoAddTo(bar);
new Button(() => { EditorGUIUtility.PingObject(c); Selection.activeObject = c; })
{ text = "定位" }.AlsoAddTo(bar);
new Button(() =>
{
string path = AssetDatabase.GetAssetPath(c);
if (!string.IsNullOrEmpty(path)) EditorGUIUtility.systemCopyBuffer = path;
}) { text = "复制路径" }.AlsoAddTo(bar);
new Button(ValidateAllChains) { text = "批量验证" }.AlsoAddTo(bar);
// 强制触发按钮仅在 Play Mode 下显示,用于调试绕过条件检查
if (Application.isPlaying)
{
var capturedC = c;
var forceBtn = new Button(() =>
{
var mgr = UnityEngine.Object.FindObjectOfType<EventChainManager>();
if (mgr == null)
{
Debug.LogWarning("[EventChainModule] 场景中未找到 EventChainManager无法强制触发。");
return;
}
Debug.Log($"[EventChainModule] 强制触发链:{capturedC.chainId}");
mgr.ForceExecute(capturedC.chainId);
}) { text = "⚡ 强制触发" };
forceBtn.style.color = new StyleColor(new Color(1f, 0.75f, 0.2f));
forceBtn.AlsoAddTo(bar);
}
var del = new Button(() =>
{
if (AssetOperations.Delete(c)) _listPane.Refresh(null);
}) { text = "删除" };
SkillModule.ApplyDeleteStyle(del);
del.AlsoAddTo(bar);
return bar;
}
// ── 批量验证 ──────────────────────────────────────────────────────────
private static void ValidateAllChains()
{
var allChains = AssetOperations.FindAll<EventChainSO>();
if (allChains.Count == 0)
{
EditorUtility.DisplayDialog("事件链验证", "项目中未找到任何 EventChainSO。", "确定");
return;
}
var issues = new List<QuestValidationResultWindow.Issue>();
int errorCount = 0, warnCount = 0;
void AddError(string msg, UnityEngine.Object asset)
{
issues.Add(new QuestValidationResultWindow.Issue { message = msg, isError = true, asset = asset });
errorCount++;
}
void AddWarn(string msg, UnityEngine.Object asset)
{
issues.Add(new QuestValidationResultWindow.Issue { message = msg, isError = false, asset = asset });
warnCount++;
}
// ① 空 chainId
foreach (var c in allChains)
if (string.IsNullOrWhiteSpace(c.chainId))
AddError($"{c.name}: chainId 为空,运行时无法存档或被 ChainCompletedCondition 引用。", c);
// ② 重复 chainId
var idMap = new Dictionary<string, EventChainSO>(StringComparer.Ordinal);
foreach (var c in allChains)
{
if (string.IsNullOrWhiteSpace(c.chainId)) continue;
if (!idMap.TryAdd(c.chainId, c))
AddError($"chainId '{c.chainId}' 重复({idMap[c.chainId].name} 与 {c.name}),运行时存档键将互串。", c);
}
// ③ 无动作
foreach (var c in allChains)
{
if (string.IsNullOrWhiteSpace(c.chainId)) continue;
if (c.actions == null || c.actions.Length == 0)
AddWarn($"{c.chainId}: actions 为空,链触发后不执行任何操作。", c);
}
// ④ conditions 含空槽
foreach (var c in allChains)
{
if (string.IsNullOrWhiteSpace(c.chainId) || c.conditions == null) continue;
for (int i = 0; i < c.conditions.Length; i++)
if (c.conditions[i] == null)
AddError($"{c.chainId}: conditions[{i}] 为 null运行时将触发 NullReferenceException。", c);
}
// ⑤ actions 含空槽
foreach (var c in allChains)
{
if (string.IsNullOrWhiteSpace(c.chainId) || c.actions == null) continue;
for (int i = 0; i < c.actions.Length; i++)
if (c.actions[i] == null)
AddError($"{c.chainId}: actions[{i}] 为 null运行时将触发 NullReferenceException。", c);
}
Debug.Log($"[EventChainModule] 验证完成:{allChains.Count} 条事件链,{errorCount} 个错误,{warnCount} 个警告。");
QuestValidationResultWindow.Show(issues, errorCount, warnCount, allChains.Count, "事件链批量验证结果", "事件链");
}
}
}

View File

@@ -0,0 +1,508 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using BaseGames.Core;
using BaseGames.Dialogue;
using BaseGames.Quest;
using BaseGames.EventChain;
using BaseGames.Editor;
namespace BaseGames.Editor.Modules
{
/// <summary>
/// DataHub 标志审计模块 —— 扫描项目所有 WorldStateFlag 引用,
/// 检测孤立标志(已注册但从未使用)和未注册标志(已使用但未在注册表定义)。
/// </summary>
public class FlagAuditModule : IDataModule, IDataModuleOrdered
{
public string ModuleId => "flagaudit";
public string DisplayName => "标志审计";
public string IconName => "d_FilterByLabel";
public int DisplayOrder => 130;
// ── 数据 ─────────────────────────────────────────────────────────────
private readonly List<FlagRecord> _records = new();
private FlagRecord _selected;
private bool _hasScanned;
private class FlagRecord
{
public string id;
public string description;
public string group;
public bool isRegistered;
public readonly List<(string label, UnityEngine.Object asset)> setLocations = new();
public readonly List<(string label, UnityEngine.Object asset)> readLocations = new();
public bool IsOrphan => isRegistered && TotalUsages == 0;
public bool IsUnregistered => !isRegistered;
public int TotalUsages => setLocations.Count + readLocations.Count;
}
// ── UI 引用 ───────────────────────────────────────────────────────────
private VisualElement _listItems;
private Label _summaryLabel;
private VisualElement _detailRoot;
private bool _filterOrphan, _filterUnregistered;
// ── IDataModule ───────────────────────────────────────────────────────
public void Initialize() { }
public void BuildListPane(VisualElement container, Action<UnityEngine.Object> onSelected)
{
// 扫描按钮
var scanBtn = new Button(RunScan) { text = "🔍 扫描标志使用情况" };
scanBtn.style.marginTop = 8;
scanBtn.style.marginLeft = 8;
scanBtn.style.marginRight = 8;
scanBtn.style.marginBottom = 4;
container.Add(scanBtn);
// 统计行
_summaryLabel = new Label("尚未扫描,点击上方按钮开始。");
_summaryLabel.style.fontSize = 10;
_summaryLabel.style.opacity = 0.6f;
_summaryLabel.style.paddingLeft = 10;
_summaryLabel.style.marginBottom = 4;
container.Add(_summaryLabel);
// 过滤标签行
var filterRow = new VisualElement();
filterRow.style.flexDirection = FlexDirection.Row;
filterRow.style.flexWrap = Wrap.Wrap;
filterRow.style.paddingLeft = 6;
filterRow.style.paddingRight = 6;
filterRow.style.paddingBottom = 3;
container.Add(filterRow);
filterRow.Add(QuestModule.MakeFilterChip("仅孤立", v => { _filterOrphan = v; RebuildList(); }));
filterRow.Add(QuestModule.MakeFilterChip("仅未注册", v => { _filterUnregistered = v; RebuildList(); }));
// 列表 ScrollView
var scroll = new ScrollView();
scroll.style.flexGrow = 1;
container.Add(scroll);
_listItems = new VisualElement();
scroll.Add(_listItems);
}
public void BuildDetailPane(VisualElement container, UnityEngine.Object selected)
{
_detailRoot = container;
RebuildDetail();
}
public void OnActivated() { }
// ── 扫描 ──────────────────────────────────────────────────────────────
private void RunScan()
{
_records.Clear();
_hasScanned = true;
var byId = new Dictionary<string, FlagRecord>(StringComparer.Ordinal);
FlagRecord GetOrCreate(string id)
{
if (!byId.TryGetValue(id, out var r))
{
r = new FlagRecord { id = id };
byId[id] = r;
_records.Add(r);
}
return r;
}
// 1. 从 WorldFlagRegistrySO 导入注册表
var registry = WorldFlagRegistrySO.EditorInstance;
if (registry?.flags != null)
foreach (var entry in registry.flags)
{
if (string.IsNullOrEmpty(entry.id)) continue;
var r = GetOrCreate(entry.id);
r.isRegistered = true;
r.description = entry.description;
r.group = entry.group;
}
// 2. 扫描 DialogueSequenceSO
foreach (var seq in AssetOperations.FindAll<DialogueSequenceSO>())
{
// variants[i].requiredFlags → 读取
if (seq.variants != null)
foreach (var v in seq.variants)
if (v.requiredFlags != null)
foreach (var fid in v.requiredFlags)
if (!string.IsNullOrEmpty(fid))
GetOrCreate(fid).readLocations.Add(($"对话变体条件 [{seq.name}]", seq));
// lines[i].choices[j].setWorldFlag → 设置
if (seq.lines != null)
foreach (var line in seq.lines)
if (line.choices != null)
foreach (var ch in line.choices)
if (!string.IsNullOrEmpty(ch.setWorldFlag))
GetOrCreate(ch.setWorldFlag).setLocations.Add(($"对话选项设置 [{seq.name}]", seq));
}
// 3. 扫描 QuestSO
foreach (var quest in AssetOperations.FindAll<QuestSO>())
{
// branches[i].conditionFlags → 读取
if (quest.branches != null)
foreach (var branch in quest.branches)
if (branch.conditionFlags != null)
foreach (var fid in branch.conditionFlags)
if (!string.IsNullOrEmpty(fid))
GetOrCreate(fid).readLocations.Add(($"任务分支条件 [{quest.name}]", quest));
// prerequisiteFlags → 读取
if (quest.prerequisiteFlags != null)
foreach (var fid in quest.prerequisiteFlags)
if (!string.IsNullOrEmpty(fid))
GetOrCreate(fid).readLocations.Add(($"任务前置标志 [{quest.name}]", quest));
}
// 4. 扫描 FlagSetConditionEventChain 条件)→ 读取
foreach (var cond in AssetOperations.FindAll<FlagSetCondition>())
if (!string.IsNullOrEmpty(cond.flagId))
GetOrCreate(cond.flagId).readLocations.Add(($"链条件 [{cond.name}]", cond));
// 5. 扫描 SetFlagActionEventChain 动作)→ 设置
foreach (var act in AssetOperations.FindAll<SetFlagAction>())
if (!string.IsNullOrEmpty(act.flagId))
GetOrCreate(act.flagId).setLocations.Add(($"链动作 [{act.name}]", act));
// 6. 扫描 NarrativeNPC 预制件中的 DialogueVersion 条件标志
// NarrativeNPC 是 MonoBehaviour使用 SerializedObject 读取序列化字段以避免反射。
var prefabGuids = AssetDatabase.FindAssets("t:Prefab", new[] { "Assets/_Game" });
foreach (var guid in prefabGuids)
{
string path = AssetDatabase.GUIDToAssetPath(guid);
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
if (prefab == null) continue;
foreach (var npc in prefab.GetComponentsInChildren<NarrativeNPC>(true))
{
var so = new SerializedObject(npc);
var vProp = so.FindProperty("_dialogueVersions");
if (vProp == null || !vProp.isArray) continue;
for (int i = 0; i < vProp.arraySize; i++)
{
var elem = vProp.GetArrayElementAtIndex(i);
var reqProp = elem.FindPropertyRelative("requiredFlags");
var blockProp = elem.FindPropertyRelative("blockedByFlags");
if (reqProp != null && reqProp.isArray)
for (int j = 0; j < reqProp.arraySize; j++)
{
string fid = reqProp.GetArrayElementAtIndex(j).stringValue;
if (!string.IsNullOrEmpty(fid))
GetOrCreate(fid).readLocations.Add(($"NPC版本条件 [{prefab.name}]", prefab));
}
if (blockProp != null && blockProp.isArray)
for (int j = 0; j < blockProp.arraySize; j++)
{
string fid = blockProp.GetArrayElementAtIndex(j).stringValue;
if (!string.IsNullOrEmpty(fid))
GetOrCreate(fid).readLocations.Add(($"NPC版本屏蔽 [{prefab.name}]", prefab));
}
}
}
}
// 排序:未注册 → 孤立 → 正常,再按 ID 字典序
_records.Sort((a, b) =>
{
int pa = a.IsUnregistered ? 0 : a.IsOrphan ? 1 : 2;
int pb = b.IsUnregistered ? 0 : b.IsOrphan ? 1 : 2;
int c = pa.CompareTo(pb);
return c != 0 ? c : string.Compare(a.id, b.id, StringComparison.Ordinal);
});
RebuildList();
RebuildDetail();
}
// ── 列表重建 ─────────────────────────────────────────────────────────
private void RebuildList()
{
if (_listItems == null) return;
_listItems.Clear();
if (!_hasScanned) return;
int total = _records.Count;
int orphanCount = _records.Count(r => r.IsOrphan);
int unregCount = _records.Count(r => r.IsUnregistered);
if (_summaryLabel != null)
_summaryLabel.text = $"共 {total} 个标志 · 孤立 {orphanCount} · 未注册 {unregCount}";
foreach (var rec in _records)
{
if (_filterOrphan && !rec.IsOrphan) continue;
if (_filterUnregistered && !rec.IsUnregistered) continue;
bool isSelected = rec == _selected;
var row = new VisualElement();
row.style.flexDirection = FlexDirection.Row;
row.style.alignItems = Align.Center;
row.style.paddingTop = 3;
row.style.paddingBottom = 3;
row.style.paddingLeft = 8;
row.style.paddingRight = 8;
row.style.backgroundColor = isSelected
? new StyleColor(new Color(0.25f, 0.5f, 1f, 0.2f))
: StyleKeyword.None;
// 状态图标 + 颜色
string icon = rec.IsUnregistered ? "⚠" : rec.IsOrphan ? "○" : "●";
Color iconColor = rec.IsUnregistered
? new Color(1f, 0.4f, 0.2f)
: rec.IsOrphan
? new Color(1f, 0.85f, 0.1f)
: new Color(0.4f, 0.85f, 0.4f);
var iconLbl = new Label(icon);
iconLbl.style.fontSize = 10;
iconLbl.style.color = new StyleColor(iconColor);
iconLbl.style.width = 14;
iconLbl.style.flexShrink = 0;
row.Add(iconLbl);
var idLbl = new Label(rec.id);
idLbl.style.fontSize = 11;
idLbl.style.flexGrow = 1;
row.Add(idLbl);
// 使用次数徽章
if (rec.TotalUsages > 0)
{
var badge = new Label(rec.TotalUsages.ToString());
badge.style.fontSize = 9;
badge.style.opacity = 0.6f;
badge.style.paddingLeft = 4;
badge.style.paddingRight = 4;
badge.style.paddingTop = 1;
badge.style.paddingBottom = 1;
badge.style.borderTopLeftRadius = 8;
badge.style.borderTopRightRadius = 8;
badge.style.borderBottomLeftRadius = 8;
badge.style.borderBottomRightRadius = 8;
badge.style.backgroundColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f, 0.25f));
row.Add(badge);
}
var capturedRec = rec;
row.RegisterCallback<ClickEvent>(_ =>
{
_selected = capturedRec;
RebuildList();
RebuildDetail();
});
_listItems.Add(row);
}
}
// ── 详情重建 ─────────────────────────────────────────────────────────
private void RebuildDetail()
{
if (_detailRoot == null) return;
_detailRoot.Clear();
if (!_hasScanned)
{
var hint = new Label("请先点击「扫描标志使用情况」按钮。");
hint.style.opacity = 0.5f;
hint.style.marginTop = 24;
hint.style.unityTextAlign = TextAnchor.UpperCenter;
_detailRoot.Add(hint);
return;
}
if (_selected == null)
{
var hint = new Label("← 从左侧选择一个标志查看详情。");
hint.style.opacity = 0.5f;
hint.style.marginTop = 24;
hint.style.unityTextAlign = TextAnchor.UpperCenter;
_detailRoot.Add(hint);
return;
}
var r = _selected;
// 标题
var titleLbl = new Label(r.id);
titleLbl.style.fontSize = 15;
titleLbl.style.unityFontStyleAndWeight = FontStyle.Bold;
titleLbl.style.paddingLeft = 12;
titleLbl.style.paddingTop = 12;
titleLbl.style.paddingBottom = 2;
_detailRoot.Add(titleLbl);
// 状态徽章
string statusText = r.IsUnregistered ? "⚠ 未在注册表中定义" : r.IsOrphan ? "○ 已注册但从未使用(孤立)" : "● 正常";
Color statusColor = r.IsUnregistered ? new Color(1f, 0.4f, 0.2f) : r.IsOrphan ? new Color(1f, 0.85f, 0.1f) : new Color(0.4f, 0.85f, 0.4f);
var statusLbl = new Label(statusText);
statusLbl.style.fontSize = 11;
statusLbl.style.color = new StyleColor(statusColor);
statusLbl.style.paddingLeft = 12;
statusLbl.style.marginBottom = 4;
_detailRoot.Add(statusLbl);
// "注册到注册表" 快捷按钮(仅未注册标志显示)
if (r.IsUnregistered)
{
var capturedRec = r;
var regBtn = new Button(() => RegisterFlagToRegistry(capturedRec))
{
text = " 注册到注册表",
tooltip = "将此标志 ID 追加到 WorldFlagRegistrySO.flags[] 中,并重新扫描。",
};
regBtn.style.marginLeft = 10;
regBtn.style.marginBottom = 6;
regBtn.style.width = 130;
_detailRoot.Add(regBtn);
}
if (!string.IsNullOrEmpty(r.group)) AddDetailRow("分组", r.group);
if (!string.IsNullOrEmpty(r.description)) AddDetailRow("描述", r.description);
_detailRoot.Add(SkillModule.MakeDivider());
AddLocationSection("📝 设置位置", r.setLocations, "无设置记录(标志只被读取,从不被写入)");
AddLocationSection("🔎 读取位置", r.readLocations, "无读取记录(标志只被写入,从不被读取)");
}
private void AddDetailRow(string label, string value)
{
var row = new VisualElement();
row.style.flexDirection = FlexDirection.Row;
row.style.paddingLeft = 12;
row.style.paddingBottom = 2;
var lbl = new Label($"{label}");
lbl.style.fontSize = 11;
lbl.style.opacity = 0.55f;
lbl.style.width = 48;
lbl.style.flexShrink = 0;
var val = new Label(value);
val.style.fontSize = 11;
val.style.flexGrow = 1;
val.style.flexWrap = Wrap.Wrap;
row.Add(lbl);
row.Add(val);
_detailRoot.Add(row);
}
private void AddLocationSection(string sectionTitle, List<(string label, UnityEngine.Object asset)> locations, string emptyText)
{
var header = new Label(sectionTitle);
header.style.fontSize = 11;
header.style.unityFontStyleAndWeight = FontStyle.Bold;
header.style.paddingLeft = 12;
header.style.paddingTop = 8;
header.style.paddingBottom = 3;
_detailRoot.Add(header);
if (locations.Count == 0)
{
var empty = new Label(emptyText);
empty.style.fontSize = 10;
empty.style.opacity = 0.45f;
empty.style.paddingLeft = 20;
empty.style.marginBottom = 4;
_detailRoot.Add(empty);
return;
}
foreach (var (lbl, asset) in locations)
{
var row = new VisualElement();
row.style.flexDirection = FlexDirection.Row;
row.style.alignItems = Align.Center;
row.style.paddingLeft = 14;
row.style.paddingRight = 8;
row.style.marginBottom = 2;
var caption = new Label(lbl);
caption.style.fontSize = 11;
caption.style.flexGrow = 1;
row.Add(caption);
if (asset != null)
{
var pingBtn = new Button(() =>
{
EditorGUIUtility.PingObject(asset);
Selection.activeObject = asset;
}) { text = "选中" };
pingBtn.style.fontSize = 10;
pingBtn.style.width = 36;
pingBtn.style.height = 18;
pingBtn.style.paddingTop = 0;
pingBtn.style.paddingBottom = 0;
row.Add(pingBtn);
}
_detailRoot.Add(row);
}
}
// ── 注册快捷操作 ──────────────────────────────────────────────────────
private void RegisterFlagToRegistry(FlagRecord rec)
{
var registry = WorldFlagRegistrySO.EditorInstance;
if (registry == null)
{
EditorUtility.DisplayDialog(
"注册表不存在",
"项目中未找到 WorldFlagRegistrySO 资产。\n" +
"请先通过 Create → BaseGames/Core/WorldFlagRegistry 创建注册表。",
"确定");
return;
}
// 检查是否已存在(理论上不可能,但防御性检查)
if (registry.flags != null)
{
foreach (var entry in registry.flags)
if (entry.id == rec.id) return;
}
var newEntry = new FlagEntry
{
id = rec.id,
description = "",
group = "",
};
var flags = registry.flags ?? System.Array.Empty<FlagEntry>();
var list = new System.Collections.Generic.List<FlagEntry>(flags) { newEntry };
Undo.RegisterCompleteObjectUndo(registry, $"注册标志 {rec.id}");
registry.flags = list.ToArray();
EditorUtility.SetDirty(registry);
AssetDatabase.SaveAssets();
// 将记录标记为已注册并重建 UI
rec.isRegistered = true;
RebuildList();
RebuildDetail();
Debug.Log($"[FlagAuditModule] 已将标志 '{rec.id}' 注册到 WorldFlagRegistrySO。");
}
}
}

View File

@@ -10,7 +10,7 @@ namespace BaseGames.Editor.Modules
/// <summary>
/// DataHub 形态模块 —— Tab 切换管理 FormConfigSO 和 FormSO 资产。
/// </summary>
public class FormModule : IDataModule
public class FormModule : IDataModule, IDataModuleOrdered
{
private const string ConfigFolder = "Assets/_Game/Data/Player/Forms";
private const string FormFolder = "Assets/_Game/Data/Player/Forms";
@@ -18,6 +18,7 @@ namespace BaseGames.Editor.Modules
public string ModuleId => "form";
public string DisplayName => "形态";
public string IconName => null;
public int DisplayOrder => 40;
private int _activeTab = 0; // 0=FormConfig, 1=FormSO

View File

@@ -0,0 +1,197 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using BaseGames.Dialogue;
using BaseGames.Quest;
using BaseGames.EventChain;
namespace BaseGames.Editor.Modules
{
/// <summary>
/// DataHub ID 生成模块 —— 扫描 QuestSO / NpcSO / DialogueSequenceSO / EventChainSO 资产,
/// 自动生成 <c>Assets/_Game/Scripts/Core/GameIds.Generated.cs</c>
/// 提供编译期 ID 常量,消除代码中的魔法字符串。
/// </summary>
public class IdCodegenModule : IDataModule, IDataModuleOrdered
{
private const string OutputPath = "Assets/_Game/Scripts/Core/GameIds.Generated.cs";
public string ModuleId => "idcodegen";
public string DisplayName => "ID 生成";
public string IconName => "d_cs Script Icon";
public int DisplayOrder => 140;
private Label _statusLabel;
private string _lastResult;
// ── IDataModule ───────────────────────────────────────────────────────
public void Initialize() { }
public void BuildListPane(VisualElement container, Action<UnityEngine.Object> onSelected)
{
var desc = new Label(
"扫描项目中的 QuestSO / NpcSO / DialogueSequenceSO / EventChainSO 资产,\n" +
$"生成 {OutputPath} 常量文件。\n\n" +
"生成后在代码中通过 GameIdsGenerated.Quest.XXX 等访问。");
desc.style.whiteSpace = WhiteSpace.Normal;
desc.style.marginBottom = 12;
desc.style.paddingLeft = 8;
desc.style.paddingRight = 8;
desc.style.fontSize = 11;
container.Add(desc);
var btn = new Button(RunCodegen) { text = "⚡ 生成 GameIds.Generated.cs" };
btn.style.marginLeft = 8;
btn.style.marginRight = 8;
btn.style.height = 28;
container.Add(btn);
_statusLabel = new Label(_lastResult ?? "");
_statusLabel.style.whiteSpace = WhiteSpace.Normal;
_statusLabel.style.marginTop = 10;
_statusLabel.style.marginLeft = 8;
_statusLabel.style.marginRight = 8;
_statusLabel.style.fontSize = 11;
container.Add(_statusLabel);
}
public void BuildDetailPane(VisualElement container, UnityEngine.Object selected)
{
// 无需详情面板
}
public void OnActivated() { }
// ── 代码生成 ──────────────────────────────────────────────────────────
private void RunCodegen()
{
try
{
var quests = AssetOperations.FindAll<QuestSO>()
.Where(q => !string.IsNullOrEmpty(q.questId))
.Select(q => q.questId)
.Distinct(StringComparer.Ordinal)
.OrderBy(s => s, StringComparer.Ordinal)
.ToList();
var npcs = AssetOperations.FindAll<NpcSO>()
.Where(n => !string.IsNullOrEmpty(n.npcId))
.Select(n => n.npcId)
.Distinct(StringComparer.Ordinal)
.OrderBy(s => s, StringComparer.Ordinal)
.ToList();
var dialogues = AssetOperations.FindAll<DialogueSequenceSO>()
.Where(d => !string.IsNullOrEmpty(d.sequenceId))
.Select(d => d.sequenceId)
.Distinct(StringComparer.Ordinal)
.OrderBy(s => s, StringComparer.Ordinal)
.ToList();
var chains = AssetOperations.FindAll<EventChainSO>()
.Where(c => !string.IsNullOrEmpty(c.chainId))
.Select(c => c.chainId)
.Distinct(StringComparer.Ordinal)
.OrderBy(s => s, StringComparer.Ordinal)
.ToList();
string code = BuildSourceCode(quests, npcs, dialogues, chains);
string fullPath = Path.GetFullPath(OutputPath);
string dir = Path.GetDirectoryName(fullPath);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
File.WriteAllText(fullPath, code, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
AssetDatabase.ImportAsset(OutputPath, ImportAssetOptions.ForceUpdate);
int total = quests.Count + npcs.Count + dialogues.Count + chains.Count;
_lastResult = $"✅ 生成完成({total} 个常量Quest×{quests.Count} Npc×{npcs.Count} " +
$"Dialogue×{dialogues.Count} Chain×{chains.Count}";
}
catch (Exception e)
{
_lastResult = $"❌ 生成失败:{e.Message}";
Debug.LogException(e);
}
if (_statusLabel != null)
_statusLabel.text = _lastResult;
}
private static string BuildSourceCode(List<string> quests, List<string> npcs,
List<string> dialogues, List<string> chains)
{
var sb = new StringBuilder();
sb.AppendLine("// <auto-generated>");
sb.AppendLine("// 此文件由 DataHub > ID生成 模块自动生成,请勿手动编辑。");
sb.AppendLine("// 手动维护的 ID 常量请放在 GameIds.cs 中。");
sb.AppendLine("// </auto-generated>");
sb.AppendLine();
sb.AppendLine("namespace BaseGames.Core");
sb.AppendLine("{");
sb.AppendLine(" /// <summary>自动生成的游戏资产 ID 常量。每次执行 DataHub > ID生成 后刷新。</summary>");
sb.AppendLine(" public static class GameIdsGenerated");
sb.AppendLine(" {");
AppendSection(sb, "Quest", "QuestSO.questId", quests, "Quest_");
AppendSection(sb, "Npc", "NpcSO.npcId", npcs, "NPC_");
AppendSection(sb, "Dialogue", "DialogueSequenceSO.sequenceId", dialogues, "DLG_");
AppendSection(sb, "Chain", "EventChainSO.chainId", chains, "Chain_");
sb.AppendLine(" }");
sb.AppendLine("}");
return sb.ToString();
}
private static void AppendSection(StringBuilder sb, string className, string docSource,
List<string> ids, string stripPrefix)
{
sb.AppendLine($" /// <summary>来自 {docSource} 的 ID 常量。</summary>");
sb.AppendLine($" public static class {className}");
sb.AppendLine(" {");
if (ids.Count == 0)
sb.AppendLine(" // 项目中暂无此类资产");
else
foreach (string id in ids)
sb.AppendLine($" public const string {ToFieldName(id, stripPrefix)} = \"{id}\";");
sb.AppendLine(" }");
sb.AppendLine();
}
/// <summary>
/// 将原始 ID 字符串转为合法的 C# 标识符。
/// 剥离常见前缀(如 "Quest_"),然后将剩余部分中的非字母数字字符替换为下划线,
/// 确保不以数字开头。
/// </summary>
private static string ToFieldName(string rawId, string stripPrefix)
{
string name = rawId;
if (!string.IsNullOrEmpty(stripPrefix) &&
name.StartsWith(stripPrefix, StringComparison.OrdinalIgnoreCase))
name = name.Substring(stripPrefix.Length);
// 将非字母数字字符替换为下划线
name = Regex.Replace(name, @"[^A-Za-z0-9_]", "_");
// 不能以数字开头
if (name.Length > 0 && char.IsDigit(name[0]))
name = "_" + name;
if (string.IsNullOrEmpty(name))
name = "_";
return name;
}
}
}

View File

@@ -0,0 +1,335 @@
using System;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using BaseGames.Dialogue;
using BaseGames.Quest;
using BaseGames.Editor.Shared;
namespace BaseGames.Editor.Modules
{
/// <summary>
/// DataHub NPC 模块 —— 管理 NpcSO 资产。
/// 统一查看、创建、重命名、删除 NPC 定义ID、名称 Key、头像、好感度上限
/// </summary>
public class NpcModule : IDataModule, IDataModuleOrdered
{
private const string Folder = "Assets/_Game/Data/NPC";
private const string Prefix = "NPC_";
public string ModuleId => "npc";
public string DisplayName => "NPC";
public string IconName => "d_GameObject Icon";
public int DisplayOrder => 90;
private SoListPane<NpcSO> _listPane;
private DetailHeader _header;
private NpcSO _selected;
public void Initialize()
{
_listPane = new SoListPane<NpcSO>(
Folder, Prefix,
n => n.maxAffinity > 0 ? $"亲密{n.maxAffinity}" : null);
// 扩展搜索npcId + nameKey
_listPane.GetExtraSearchText = n => $"{n.npcId} {n.nameKey}";
}
public void BuildListPane(VisualElement container, Action<UnityEngine.Object> onSelected)
{
_listPane.SelectionChanged = sel =>
{
_selected = sel;
onSelected?.Invoke(sel);
};
// ── 快速过滤标签行 ─────────────────────────────────────────────
var filterRow = new VisualElement();
filterRow.style.flexDirection = FlexDirection.Row;
filterRow.style.flexWrap = Wrap.Wrap;
filterRow.style.paddingLeft = 6;
filterRow.style.paddingRight = 6;
filterRow.style.paddingBottom = 3;
container.Add(filterRow);
bool filterAffinity = false, filterPortrait = false;
void RebuildFilter()
{
if (!filterAffinity && !filterPortrait)
{
_listPane.ExtraFilter = null;
return;
}
_listPane.ExtraFilter = n =>
{
if (filterAffinity && n.maxAffinity <= 0) return false;
if (filterPortrait && n.portrait == null) return false;
return true;
};
}
filterRow.Add(QuestModule.MakeFilterChip("有好感度", v => { filterAffinity = v; RebuildFilter(); }));
filterRow.Add(QuestModule.MakeFilterChip("有头像", v => { filterPortrait = v; RebuildFilter(); }));
container.Add(_listPane);
_listPane.Refresh();
}
public void BuildDetailPane(VisualElement container, UnityEngine.Object selected)
{
_selected = selected as NpcSO;
_header = new DetailHeader();
_header.SetAsset(_selected);
_header.RenameRequested += OnRenameRequested;
container.Add(_header);
if (_selected == null) return;
container.Add(BuildInfoCard(_selected));
container.Add(BuildActionBar(_selected));
container.Add(SkillModule.MakeDivider());
container.Add(new InspectorElement(_selected));
}
public void OnActivated() => _listPane?.Refresh();
// ── 内部 ──────────────────────────────────────────────────────────────
private void OnRenameRequested(string newName)
{
if (_selected == null) return;
var (ok, err) = AssetOperations.Rename(_selected, newName);
if (!ok) EditorUtility.DisplayDialog("重命名失败", err, "确定");
else { _header.SetAsset(_selected); _listPane.Invalidate(); }
}
private static VisualElement BuildInfoCard(NpcSO n)
{
var card = SkillModule.MakeCard();
SkillModule.AddChip(card, "NPC ID", string.IsNullOrEmpty(n.npcId) ? "(未设置)" : n.npcId);
string nameDisplay = string.IsNullOrEmpty(n.nameKey)
? "(未设置)"
: (BaseGames.Localization.LocalizationManager.GetEditorPreview(n.nameKey, "Dialogue") ?? n.nameKey);
SkillModule.AddChip(card, "名称", nameDisplay);
if (!string.IsNullOrEmpty(n.nameKey))
SkillModule.AddChip(card, "名称 Key", n.nameKey);
if (n.maxAffinity > 0)
SkillModule.AddChip(card, "好感度上限", n.maxAffinity.ToString());
// 头像预览
if (n.portrait != null)
{
var row = new VisualElement();
row.style.flexDirection = FlexDirection.Row;
row.style.alignItems = Align.Center;
row.style.paddingLeft = 8;
row.style.paddingTop = 4;
var img = new Image { image = n.portrait.texture };
img.style.width = 40;
img.style.height = 40;
img.style.borderTopLeftRadius = 4;
img.style.borderTopRightRadius = 4;
img.style.borderBottomLeftRadius = 4;
img.style.borderBottomRightRadius = 4;
row.Add(img);
card.Add(row);
}
// 关联任务反查:显示哪些任务以此 NPC 为发布者
var referencingQuests = FindQuestsReferencingNpc(n);
if (referencingQuests.Count > 0)
{
SkillModule.AddChip(card, "关联任务", $"共 {referencingQuests.Count} 个");
var refFold = new UnityEngine.UIElements.Foldout
{
text = $"关联任务({referencingQuests.Count}",
value = false,
};
refFold.style.paddingLeft = 8;
foreach (var q in referencingQuests)
{
var btn = new UnityEngine.UIElements.Button(() => UnityEditor.EditorGUIUtility.PingObject(q))
{
text = string.IsNullOrEmpty(q.questId) ? q.name : $"{q.questId} ({q.name})"
};
btn.style.unityTextAlign = UnityEngine.TextAnchor.MiddleLeft;
btn.style.fontSize = 10;
btn.style.marginBottom = 1;
refFold.Add(btn);
}
card.Add(refFold);
}
return card;
}
// ── 关联任务缓存5 秒 TTL避免每次切换 NPC 时全量扫描资产数据库)──────────────
private static System.Collections.Generic.Dictionary<NpcSO, System.Collections.Generic.List<QuestSO>>
s_npcQuestCache;
private static double s_npcQuestCacheTime = -10.0;
private static System.Collections.Generic.List<QuestSO> FindQuestsReferencingNpc(NpcSO n)
{
double now = UnityEditor.EditorApplication.timeSinceStartup;
if (s_npcQuestCache != null && now - s_npcQuestCacheTime < 5.0)
{
s_npcQuestCache.TryGetValue(n, out var cached);
return cached ?? new System.Collections.Generic.List<QuestSO>();
}
// TTL 过期,重建全量缓存(单次扫描所有 QuestSO分组存储
s_npcQuestCache = new System.Collections.Generic.Dictionary<NpcSO, System.Collections.Generic.List<QuestSO>>();
var guids = UnityEditor.AssetDatabase.FindAssets("t:QuestSO");
foreach (var guid in guids)
{
var path = UnityEditor.AssetDatabase.GUIDToAssetPath(guid);
var q = UnityEditor.AssetDatabase.LoadAssetAtPath<QuestSO>(path);
if (q == null || q.giverNpc == null) continue;
if (!s_npcQuestCache.TryGetValue(q.giverNpc, out var list))
{
list = new System.Collections.Generic.List<QuestSO>();
s_npcQuestCache[q.giverNpc] = list;
}
list.Add(q);
}
s_npcQuestCacheTime = now;
s_npcQuestCache.TryGetValue(n, out var result);
return result ?? new System.Collections.Generic.List<QuestSO>();
}
private VisualElement BuildActionBar(NpcSO n)
{
var bar = SkillModule.BuildStandardActionBar(
n, Folder, Prefix,
onCreated: c => _listPane.Refresh(c),
onCloned: c => _listPane.Refresh(c),
onDeleted: () => _listPane.Refresh(null),
wizardCreate: cb => AssetCreationWizard.Show<NpcSO>(
Folder, Prefix,
(npc, id) =>
{
npc.npcId = id;
EditorUtility.SetDirty(npc);
AssetDatabase.SaveAssets();
cb(npc);
}));
// 批量验证按钮
var validateBtn = new Button(ValidateAllNpcs) { text = "批量验证" };
validateBtn.style.marginLeft = 4;
bar.Add(validateBtn);
return bar;
}
// ── 批量验证 ─────────────────────────────────────────────────────────
/// <summary>
/// 遍历所有 NpcSO检查
/// 1. npcId 为空
/// 2. npcId 重复(全局)
/// 3. nameKey 为空NPC 无显示名称)
/// 4. maxAffinity > 0 但 portrait 为 null好感度 UI 无头像可展示)
/// 5. nameKey 在本地化表中不存在
/// 6. interactPromptKey 非空但在本地化表中不存在
/// 7. 与同 npcId 的 DialogueActorSO portrait 不一致
/// 结果在 QuestValidationResultWindow 中展示,每项问题附"选中"按钮可一键定位资产。
/// </summary>
private static void ValidateAllNpcs()
{
var allNpcs = AssetOperations.FindAll<NpcSO>();
var issues = new System.Collections.Generic.List<QuestValidationResultWindow.Issue>();
int errorCount = 0, warnCount = 0;
void AddError(string msg, UnityEngine.Object asset = null)
{
issues.Add(new QuestValidationResultWindow.Issue { message = msg, isError = true, asset = asset });
errorCount++;
}
void AddWarn(string msg, UnityEngine.Object asset = null)
{
issues.Add(new QuestValidationResultWindow.Issue { message = msg, isError = false, asset = asset });
warnCount++;
}
// 预构建本地化缓存(单次查询,整个验证过程复用)
var locCache = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.Ordinal);
string GetLoc(string key)
{
if (locCache.TryGetValue(key, out var v)) return v;
v = BaseGames.Localization.LocalizationManager.GetEditorPreview(key, "Dialogue");
locCache[key] = v;
return v;
}
// 预构建 DialogueActorSO 映射 actorId → ActorSO用于 portrait 一致性检查)
var actorMap = new System.Collections.Generic.Dictionary<string, BaseGames.Dialogue.DialogueActorSO>(
System.StringComparer.Ordinal);
var actorGuids = UnityEditor.AssetDatabase.FindAssets("t:DialogueActorSO");
foreach (var g in actorGuids)
{
var path = UnityEditor.AssetDatabase.GUIDToAssetPath(g);
var actor = UnityEditor.AssetDatabase.LoadAssetAtPath<BaseGames.Dialogue.DialogueActorSO>(path);
if (actor != null && !string.IsNullOrEmpty(actor.actorId) && !actorMap.ContainsKey(actor.actorId))
actorMap[actor.actorId] = actor;
}
// 1 & 2空 npcId / 重复 npcId
var idMap = new System.Collections.Generic.Dictionary<string, NpcSO>(System.StringComparer.Ordinal);
foreach (var n in allNpcs)
{
if (string.IsNullOrWhiteSpace(n.npcId))
{
AddError($"{n.name}: npcId 为空NPC 无法被系统引用。", n);
continue;
}
if (idMap.TryGetValue(n.npcId, out var existing))
AddError($"重复 npcId \"{n.npcId}\"{n.name} 与 {existing.name}", n);
else
idMap[n.npcId] = n;
}
// 3-7其余字段检查
foreach (var n in allNpcs)
{
// 3. nameKey 为空
if (string.IsNullOrEmpty(n.nameKey))
AddWarn($"{n.name}{n.npcId}: nameKey 为空,运行时显示空名称。", n);
// 4. 有好感度但无头像
if (n.maxAffinity > 0 && n.portrait == null)
AddWarn($"{n.name}{n.npcId}: maxAffinity={n.maxAffinity} 但 portrait 为 null好感度进度条 UI 无头像可展示。", n);
// 5. nameKey 本地化不存在
if (!string.IsNullOrEmpty(n.nameKey) && GetLoc(n.nameKey) == null)
AddWarn($"{n.name}{n.npcId}: nameKey \"{n.nameKey}\" 在本地化表中不存在。", n);
// 5b. nameKey 格式异常(含空格或非法字符)
if (!string.IsNullOrEmpty(n.nameKey) &&
!System.Text.RegularExpressions.Regex.IsMatch(n.nameKey, @"^[\w\-\.]+$"))
AddWarn($"{n.name}{n.npcId}: nameKey \"{n.nameKey}\" 含有空格或非法字符建议只使用字母、数字、_、-、.。", n);
// 6. interactPromptKey 本地化不存在
if (!string.IsNullOrEmpty(n.interactPromptKey) && GetLoc(n.interactPromptKey) == null)
AddWarn($"{n.name}{n.npcId}: interactPromptKey \"{n.interactPromptKey}\" 在本地化表中不存在,运行时交互提示显示 Key 原文。", n);
// 7. portrait 与同 npcId 的 DialogueActorSO 不一致
if (!string.IsNullOrEmpty(n.npcId) && actorMap.TryGetValue(n.npcId, out var actor))
{
if (actor.portrait != n.portrait)
AddWarn($"{n.name}{n.npcId}: portrait 与 DialogueActorSO \"{actor.name}\" 的 portrait 不一致," +
"对话框中显示的头像与 NPC 信息面板头像可能不同。", n);
}
}
UnityEngine.Debug.Log($"[NpcModule] 验证完成:{allNpcs.Count} 个 NPC{errorCount} 个错误,{warnCount} 个警告。");
QuestValidationResultWindow.Show(issues, errorCount, warnCount, allNpcs.Count, "NPC 批量验证结果", "NPC");
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5d7d769256156a542bf7efb80f93f3c4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -7,13 +7,14 @@ using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using BaseGames.Quest;
using BaseGames.Editor.Shared;
namespace BaseGames.Editor.Modules
{
/// <summary>
/// DataHub 任务模块 —— 管理 QuestSO 资产。
/// </summary>
public class QuestModule : IDataModule
public class QuestModule : IDataModule, IDataModuleOrdered
{
private const string Folder = "Assets/_Game/Data/Quest";
private const string Prefix = "Quest_";
@@ -21,11 +22,15 @@ namespace BaseGames.Editor.Modules
public string ModuleId => "quest";
public string DisplayName => "任务";
public string IconName => "d_UnityEditor.InspectorWindow";
public int DisplayOrder => 110;
private SoListPane<QuestSO> _listPane;
private DetailHeader _header;
private QuestSO _selected;
// playModeStateChanged 订阅的字段引用,便于在重建 ActionBar 时退订旧订阅,避免内存泄漏
private System.Action<UnityEditor.PlayModeStateChange> _playModeHandler;
public void Initialize()
{
_listPane = new SoListPane<QuestSO>(
@@ -33,8 +38,20 @@ namespace BaseGames.Editor.Modules
s =>
{
bool hasPre = s.prerequisiteQuests != null && s.prerequisiteQuests.Length > 0;
// 徽章:分类 + 有前置
string catLabel = s.category switch
{
QuestCategory.Main => "主线",
QuestCategory.Daily => "日常",
QuestCategory.Hidden => "隐藏",
_ => null, // Side 不显示(默认值,减少视觉噪声)
};
if (catLabel != null) return catLabel;
return hasPre ? "有前置" : null;
});
// 扩展搜索questId + displayNameKey + category
_listPane.GetExtraSearchText = q =>
$"{q.questId} {q.displayNameKey} {q.category}";
}
public void BuildListPane(VisualElement container, Action<UnityEngine.Object> onSelected)
@@ -44,10 +61,93 @@ namespace BaseGames.Editor.Modules
_selected = sel;
onSelected?.Invoke(sel);
};
// ── 快速过滤标签行 ─────────────────────────────────────────────
var filterRow = new VisualElement();
filterRow.style.flexDirection = FlexDirection.Row;
filterRow.style.flexWrap = Wrap.Wrap;
filterRow.style.paddingLeft = 6;
filterRow.style.paddingRight = 6;
filterRow.style.paddingBottom = 3;
container.Add(filterRow);
bool filterPrereq = false, filterNoObj = false, filterCanFail = false;
QuestCategory? filterCategory = null;
void RebuildFilter()
{
if (!filterPrereq && !filterNoObj && !filterCanFail && filterCategory == null)
{
_listPane.ExtraFilter = null;
return;
}
_listPane.ExtraFilter = q =>
{
if (filterPrereq && (q.prerequisiteQuests == null || q.prerequisiteQuests.Length == 0)) return false;
if (filterNoObj && (q.objectives != null && q.objectives.Length > 0)) return false;
if (filterCanFail && !q.canFail) return false;
if (filterCategory.HasValue && q.category != filterCategory.Value) return false;
return true;
};
}
filterRow.Add(MakeFilterChip("主线", v => { filterCategory = v ? QuestCategory.Main : (QuestCategory?)null; RebuildFilter(); }));
filterRow.Add(MakeFilterChip("支线", v => { filterCategory = v ? QuestCategory.Side : (QuestCategory?)null; RebuildFilter(); }));
filterRow.Add(MakeFilterChip("日常", v => { filterCategory = v ? QuestCategory.Daily : (QuestCategory?)null; RebuildFilter(); }));
filterRow.Add(MakeFilterChip("隐藏", v => { filterCategory = v ? QuestCategory.Hidden : (QuestCategory?)null; RebuildFilter(); }));
// 分隔
var sep = new Label("|");
sep.style.opacity = 0.3f;
sep.style.marginLeft = 2;
sep.style.marginRight = 2;
filterRow.Add(sep);
filterRow.Add(MakeFilterChip("有前置", v => { filterPrereq = v; RebuildFilter(); }));
filterRow.Add(MakeFilterChip("无目标", v => { filterNoObj = v; RebuildFilter(); }));
filterRow.Add(MakeFilterChip("可失败", v => { filterCanFail = v; RebuildFilter(); }));
container.Add(_listPane);
_listPane.Refresh();
}
internal static VisualElement MakeFilterChip(string label, System.Action<bool> onToggle)
{
bool active = false;
var chip = new Label(label);
chip.style.fontSize = 10;
chip.style.paddingLeft = 6;
chip.style.paddingRight = 6;
chip.style.paddingTop = 2;
chip.style.paddingBottom = 2;
chip.style.marginRight = 4;
chip.style.marginBottom = 2;
chip.style.borderTopLeftRadius = 8;
chip.style.borderTopRightRadius = 8;
chip.style.borderBottomLeftRadius = 8;
chip.style.borderBottomRightRadius = 8;
chip.style.borderTopWidth = 1;
chip.style.borderRightWidth = 1;
chip.style.borderBottomWidth = 1;
chip.style.borderLeftWidth = 1;
chip.style.borderTopColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f, 0.4f));
chip.style.borderRightColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f, 0.4f));
chip.style.borderBottomColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f, 0.4f));
chip.style.borderLeftColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f, 0.4f));
chip.style.opacity = 0.6f;
void SetActive(bool on)
{
active = on;
chip.style.opacity = on ? 1f : 0.6f;
chip.style.backgroundColor = on
? new StyleColor(new Color(0.3f, 0.6f, 1f, 0.25f))
: StyleKeyword.None;
onToggle(on);
}
chip.RegisterCallback<ClickEvent>(_ => SetActive(!active));
return chip;
}
public void BuildDetailPane(VisualElement container, UnityEngine.Object selected)
{
_selected = selected as QuestSO;
@@ -63,6 +163,7 @@ namespace BaseGames.Editor.Modules
container.Add(BuildObjectivesList(_selected));
if (_selected.branches != null && _selected.branches.Length > 0)
container.Add(BuildBranchesCard(_selected));
container.Add(BuildDependencyGraph(_selected));
container.Add(BuildActionBar(_selected));
container.Add(SkillModule.MakeDivider());
container.Add(new InspectorElement(_selected));
@@ -86,11 +187,42 @@ namespace BaseGames.Editor.Modules
int objCount = s.objectives != null ? s.objectives.Length : 0;
SkillModule.AddChip(card, "ID", string.IsNullOrEmpty(s.questId) ? "(未设置)" : s.questId);
SkillModule.AddChip(card, "名称 Key", string.IsNullOrEmpty(s.displayNameKey) ? "(未设置)" : s.displayNameKey);
// 名称:优先显示本地化实际文本,回退到 Key 本身(与 ActorModule 保持一致)
string nameDisplay;
if (string.IsNullOrEmpty(s.displayNameKey))
{
nameDisplay = "(未设置)";
}
else
{
var resolved = BaseGames.Localization.LocalizationManager.GetEditorPreview(s.displayNameKey, "Quest");
nameDisplay = resolved != null ? resolved : s.displayNameKey + " ⚠ [缺少本地化]";
}
SkillModule.AddChip(card, "名称", nameDisplay);
if (!string.IsNullOrEmpty(s.displayNameKey))
SkillModule.AddChip(card, "名称 Key", s.displayNameKey);
if (!string.IsNullOrEmpty(s.descriptionKey))
SkillModule.AddChip(card, "描述 Key", s.descriptionKey);
SkillModule.AddChip(card, "目标数", objCount.ToString());
// 分类标签
string catDisplay = s.category switch
{
QuestCategory.Main => "主线",
QuestCategory.Side => "支线",
QuestCategory.Daily => "日常",
QuestCategory.Hidden => "隐藏",
_ => s.category.ToString(),
};
SkillModule.AddChip(card, "分类", catDisplay);
// 发布 NPC优先显示 giverNpc.npcId回退旧 giverNpcId
string giverId = s.GiverNpcId;
if (!string.IsNullOrEmpty(giverId))
SkillModule.AddChip(card, "发布 NPC", giverId);
if (s.prerequisiteQuests != null && s.prerequisiteQuests.Length > 0)
{
// 显示每个前置任务的 questId方便策划一眼看清依赖链
@@ -110,7 +242,24 @@ namespace BaseGames.Editor.Modules
if (s.canFail)
SkillModule.AddChip(card, "可失败", "✓");
if (s.reward != null)
SkillModule.AddChip(card, "奖励", s.reward.name);
{
SkillModule.AddChip(card, "奖励资产", s.reward.name);
// 展示奖励具体内容,方便策划确认配置
var rewardDetail = new System.Text.StringBuilder();
if (s.reward.lingZhu > 0) rewardDetail.Append($"灵珠×{s.reward.lingZhu} ");
if (s.reward.soulBonus > 0) rewardDetail.Append($"灵魂槽+{s.reward.soulBonus} ");
if (s.reward.itemIds != null && s.reward.itemIds.Length > 0)
rewardDetail.Append($"物品×{s.reward.itemIds.Length} ");
if (s.reward.affinityBonus != 0)
rewardDetail.Append($"好感{(s.reward.affinityBonus > 0 ? "+" : "")}{s.reward.affinityBonus} ");
if (s.reward.unlocksAbility)
rewardDetail.Append("能力解锁 ");
if (!string.IsNullOrEmpty(s.reward.unlockDialogueKey))
rewardDetail.Append("台词解锁 ");
string detail = rewardDetail.ToString().TrimEnd();
if (!string.IsNullOrEmpty(detail))
SkillModule.AddChip(card, "奖励内容", detail);
}
return card;
}
@@ -185,6 +334,23 @@ namespace BaseGames.Editor.Modules
}
section.Add(row);
// 目标描述(本地化预览,灰色小字,显示策划填写的实际内容)
if (!string.IsNullOrEmpty(obj.displayTextKey))
{
var resolved = BaseGames.Localization.LocalizationManager.GetEditorPreview(obj.displayTextKey, "Quest");
bool l10nMissing = resolved == null;
string descText = l10nMissing ? obj.displayTextKey + " ⚠ [缺少本地化]" : resolved;
var desc = new Label(descText);
desc.style.fontSize = 10;
desc.style.opacity = l10nMissing ? 1.0f : 0.55f;
desc.style.color = l10nMissing
? new StyleColor(new Color(1f, 0.6f, 0.1f))
: new StyleColor(StyleKeyword.Null);
desc.style.paddingLeft = 26;
desc.style.marginBottom = 2;
section.Add(desc);
}
}
return section;
@@ -226,20 +392,508 @@ namespace BaseGames.Editor.Modules
return card;
}
/// <summary>
/// 构建当前任务的依赖关系可视图(折叠面板形式):
/// - 上方:前置任务链(此任务需要哪些任务先完成)
/// - 下方:后续任务链(此任务完成后可解锁哪些任务)
/// 数据来源allQuests 中所有 QuestSO 的 prerequisiteQuests 引用,无运行时副作用。
/// 节点可点击→选中对应资产EditorGUIUtility.PingObject
/// </summary>
private static VisualElement BuildDependencyGraph(QuestSO s)
{
var foldout = new Foldout { text = "依赖关系", value = false };
foldout.style.paddingLeft = 12;
foldout.style.paddingRight = 12;
foldout.style.marginTop = 4;
foldout.style.marginBottom = 4;
// 懒加载:展开时才扫描资产,避免初始化开销
bool built = false;
foldout.RegisterValueChangedCallback(evt =>
{
if (!evt.newValue || built) return;
built = true;
PopulateDependencyGraph(foldout.contentContainer, s);
});
return foldout;
}
private static void PopulateDependencyGraph(VisualElement container, QuestSO s)
{
var allQuests = AssetOperations.FindAll<QuestSO>();
// ── 前置任务(上游)────────────────────────────────────────────────
bool hasPrereqs = s.prerequisiteQuests != null && s.prerequisiteQuests.Length > 0;
AddDepSection(container, "▲ 前置任务(需先完成)",
hasPrereqs
? System.Array.ConvertAll(s.prerequisiteQuests, q => (q, "前置"))
: null,
hasPrereqs ? null : "(无前置条件,可直接接取)");
// ── 后续任务(下游):扫描 allQuests找出以 s 为前置的任务 ───────
var downstream = new List<(QuestSO q, string label)>();
foreach (var quest in allQuests)
{
if (quest == null || quest == s) continue;
if (quest.prerequisiteQuests == null) continue;
foreach (var pre in quest.prerequisiteQuests)
{
if (pre == s) { downstream.Add((quest, "解锁")); break; }
}
}
// ── 分支后续branch.nextQuest────────────────────────────────────
if (s.branches != null)
{
foreach (var branch in s.branches)
{
if (branch.nextQuest == null) continue;
string label = branch.conditionQuest != null
? $"分支(条件={branch.conditionQuest.questId}"
: "分支(默认)";
downstream.Add((branch.nextQuest, label));
}
}
AddDepSection(container, "▼ 后续任务(完成后解锁)",
downstream.Count > 0 ? downstream.ToArray() : null,
downstream.Count == 0 ? "(无后续任务)" : null);
// ── 环形依赖检测 ─────────────────────────────────────────────────
// 检查当前任务的前置链中是否存在循环引用(如 A 需要 BB 又需要 A
if (HasPrerequisiteCycle(s, s, new System.Collections.Generic.HashSet<string>(System.StringComparer.Ordinal)))
{
var cycleWarn = new UnityEngine.UIElements.Label("⚠ 检测到前置任务循环引用!此任务永远无法接取,请检查前置任务链。");
cycleWarn.style.color = new StyleColor(new UnityEngine.Color(1f, 0.4f, 0.2f));
cycleWarn.style.fontSize = 11;
cycleWarn.style.marginTop = 6;
cycleWarn.style.paddingLeft = 8;
cycleWarn.style.whiteSpace = WhiteSpace.Normal;
container.Add(cycleWarn);
}
}
/// <summary>
/// 递归检测任务是否存在循环前置依赖DFS
/// visited 存储已访问的 questIdorigin 为检测起点。
/// </summary>
private static bool HasPrerequisiteCycle(QuestSO origin, QuestSO current, System.Collections.Generic.HashSet<string> visited)
{
if (current?.prerequisiteQuests == null) return false;
foreach (var pre in current.prerequisiteQuests)
{
if (pre == null || string.IsNullOrEmpty(pre.questId)) continue;
if (pre == origin) return true; // 回到起点,发现循环
if (!visited.Add(pre.questId)) continue; // 已访问,跳过防止重复 DFS
if (HasPrerequisiteCycle(origin, pre, visited)) return true;
}
return false;
}
/// <summary>添加一个依赖关系分区(标题 + 节点列表)。</summary>
private static void AddDepSection(VisualElement container,
string sectionTitle,
(QuestSO q, string label)[] items,
string emptyText)
{
var header = new Label(sectionTitle);
header.style.fontSize = 10;
header.style.opacity = 0.55f;
header.style.marginTop = 6;
header.style.marginBottom = 3;
header.style.unityFontStyleAndWeight = FontStyle.Bold;
container.Add(header);
if (items == null || items.Length == 0)
{
var empty = new Label(emptyText ?? "(无)");
empty.style.fontSize = 11;
empty.style.opacity = 0.4f;
empty.style.paddingLeft = 10;
container.Add(empty);
return;
}
foreach (var (q, label) in items)
{
if (q == null) continue;
var row = new VisualElement();
row.style.flexDirection = FlexDirection.Row;
row.style.alignItems = Align.Center;
row.style.marginBottom = 2;
row.style.paddingLeft = 10;
// 关系标签徽章
var badge = new Label($"[{label}]");
badge.style.fontSize = 9;
badge.style.opacity = 0.6f;
badge.style.marginRight = 5;
badge.style.flexShrink = 0;
row.Add(badge);
// 任务名按钮(点击 Ping 资产)
string displayName = string.IsNullOrEmpty(q.questId) ? q.name : q.questId;
var btn = new Button(() => EditorGUIUtility.PingObject(q)) { text = displayName };
btn.style.fontSize = 11;
btn.style.flexGrow = 1;
btn.style.paddingTop = 1;
btn.style.paddingBottom = 1;
btn.style.unityTextAlign = TextAnchor.MiddleLeft;
row.Add(btn);
container.Add(row);
}
}
private VisualElement BuildActionBar(QuestSO s)
{
var bar = SkillModule.BuildStandardActionBar(
s, Folder, Prefix,
onCreated: c => _listPane.Refresh(c),
onCloned: c => _listPane.Refresh(c),
onDeleted: () => _listPane.Refresh(null));
onDeleted: () => _listPane.Refresh(null),
wizardCreate: cb => AssetCreationWizard.Show<QuestSO>(
Folder, Prefix,
(q, id) =>
{
q.questId = id;
EditorUtility.SetDirty(q);
AssetDatabase.SaveAssets();
cb(q);
}));
// 任务模块额外:代码常量生成
new Button(GenerateQuestKeys) { text = "生成常量" }.AlsoAddTo(bar);
// 任务模块额外:代码常量生成 + 批量配置验证
new Button(GenerateQuestKeys) { text = "生成常量" }.AlsoAddTo(bar);
new Button(ValidateAllQuests) { text = "批量验证" }.AlsoAddTo(bar);
// 运行时模拟按钮(仅 PlayMode 可用)
var simulateBtn = new Button(() => SimulateQuest(_selected)) { text = "▶ 模拟" };
simulateBtn.tooltip =
"PlayMode 下推进任务状态机:\n" +
" • Available → AcceptQuest接取\n" +
" • Active → 弹窗选择CompleteQuest 或 AbandonQuest\n" +
" • 其他状态 → ResetQuest重置为 Available 供重测)\n" +
"EditMode 下按钮灰显。";
simulateBtn.SetEnabled(UnityEditor.EditorApplication.isPlaying);
// 退订旧订阅,避免每次 BuildDetailPane 时重复追加 lambda 导致内存泄漏
if (_playModeHandler != null)
UnityEditor.EditorApplication.playModeStateChanged -= _playModeHandler;
_playModeHandler = s =>
{
bool playing = s == UnityEditor.PlayModeStateChange.EnteredPlayMode
|| UnityEditor.EditorApplication.isPlaying;
simulateBtn.SetEnabled(playing);
};
UnityEditor.EditorApplication.playModeStateChanged += _playModeHandler;
simulateBtn.AlsoAddTo(bar);
return bar;
}
// ── 运行时模拟 ────────────────────────────────────────────────────────
/// <summary>
/// PlayMode 下对当前选中的 QuestSO 模拟状态推进或重置:
/// - Available → AcceptQuest
/// - Active → CompleteQuest传入 null rewardTarget跳过奖励发放
/// - Completed / Failed / Unavailable → ResetQuest重置为 Available 供重测)
/// 用于策划/开发人员在不启动游戏流程的情况下快速验证任务状态机。
/// </summary>
private static void SimulateQuest(QuestSO quest)
{
if (!UnityEditor.EditorApplication.isPlaying)
{
UnityEditor.EditorUtility.DisplayDialog("模拟测试", "请先进入 PlayMode。", "确定");
return;
}
if (quest == null)
{
Debug.LogWarning("[QuestModule] 请先在左侧列表选中一个任务再点击模拟。");
return;
}
var qm = BaseGames.Core.ServiceLocator.GetOrDefault<IQuestManager>();
if (qm == null)
{
Debug.LogWarning("[QuestModule] IQuestManager 未注册到 ServiceLocator请确认 QuestManager 已在场景中。");
return;
}
var state = qm.GetState(quest.questId);
switch (state)
{
case BaseGames.Core.Events.QuestState.Available:
qm.AcceptQuest(quest.questId);
Debug.Log($"[QuestModule] 模拟接受任务:{quest.questId}");
break;
case BaseGames.Core.Events.QuestState.Active:
// Active 状态提供三个操作:完成 / 暂停 / 放弃
int choice = UnityEditor.EditorUtility.DisplayDialogComplex(
"模拟 Active 任务",
$"任务 [{quest.questId}] 当前进行中,请选择操作:",
"完成任务", // 0
"取消", // 1
"暂停任务"); // 2
if (choice == 0)
{
qm.CompleteQuest(quest.questId, null);
Debug.Log($"[QuestModule] 模拟完成任务:{quest.questId}");
}
else if (choice == 2)
{
qm.PauseQuest(quest.questId);
Debug.Log($"[QuestModule] 模拟暂停任务:{quest.questId}");
}
break;
case BaseGames.Core.Events.QuestState.Paused:
// Paused 状态:恢复 或 放弃
int pauseChoice = UnityEditor.EditorUtility.DisplayDialogComplex(
"模拟 Paused 任务",
$"任务 [{quest.questId}] 当前已暂停,请选择操作:",
"恢复任务", // 0
"取消", // 1
"放弃任务"); // 2
if (pauseChoice == 0)
{
qm.ResumeQuest(quest.questId);
Debug.Log($"[QuestModule] 模拟恢复任务:{quest.questId}");
}
else if (pauseChoice == 2)
{
// Paused 不能直接调用 AbandonQuest需先恢复
qm.ResumeQuest(quest.questId);
qm.AbandonQuest(quest.questId);
Debug.Log($"[QuestModule] 模拟放弃暂停中的任务:{quest.questId}");
}
break;
default:
// Completed / Failed / Unavailable → 通过 IQuestDebugger 重置为 Available 供重测
#if UNITY_EDITOR || DEVELOPMENT_BUILD
if (qm is IQuestDebugger debugger)
{
debugger.ResetQuest(quest.questId);
Debug.Log($"[QuestModule] 任务 '{quest.questId}' 已从 [{state}] 重置,可重新接取。");
}
else
{
Debug.LogWarning($"[QuestModule] IQuestManager 未实现 IQuestDebugger无法重置任务 '{quest.questId}'。");
}
#endif
break;
}
}
// ── 批量验证 ─────────────────────────────────────────────────────────
/// <summary>
/// 遍历所有 QuestSO执行以下检查并汇总结果
/// 1. questId 为空
/// 2. questId 重复
/// 3. objectives 为空(无目标任务)
/// 4. prerequisiteQuests 含空引用
/// 5. 前置任务循环依赖DFS
/// 6. canFail=true 但 failCondition 为空
/// 7. reward.affinityBonus != 0 但 giverNpcId 为空(好感度会丢失)
/// 8. TriggerZone ↔ ReachAreaObjective markerTag 孤儿交叉检测
/// 9. 同任务内 objectiveId 重复(运行时 compositeKey 碰撞)
/// 10. branches[i].conditionFlags 含空白字符串(策划配置遗漏 flag 名)
/// 11. reward.itemIds 含空白字符串或无对应 Collectible 预制件(孤儿奖励 ID
/// 结果在可交互的 QuestValidationResultWindow 中展示,每项问题附"选中"按钮可一键定位资产。
/// </summary>
private static void ValidateAllQuests()
{
var allQuests = AssetOperations.FindAll<QuestSO>();
var issues = new List<QuestValidationResultWindow.Issue>();
int errorCount = 0, warnCount = 0;
void AddError(string msg, UnityEngine.Object asset = null)
{
issues.Add(new QuestValidationResultWindow.Issue { message = msg, isError = true, asset = asset });
errorCount++;
}
void AddWarn(string msg, UnityEngine.Object asset = null)
{
issues.Add(new QuestValidationResultWindow.Issue { message = msg, isError = false, asset = asset });
warnCount++;
}
var idMap = ValidateIds(allQuests, AddError);
ValidateStructure(allQuests, idMap, AddError, AddWarn);
ValidateTriggerZones(AddWarn);
ValidateObjectiveIds(allQuests, AddError);
ValidateBranchFlags(allQuests, AddWarn);
ValidateRewards(allQuests, AddWarn);
Debug.Log($"[QuestModule] 验证完成:{allQuests.Count} 个任务,{errorCount} 个错误,{warnCount} 个警告。");
QuestValidationResultWindow.Show(issues, errorCount, warnCount, allQuests.Count, "任务批量验证结果", "任务");
}
// 检查 1 & 2空 questId / 重复 questId返回 id→SO 映射供后续检查使用
private static Dictionary<string, QuestSO> ValidateIds(
List<QuestSO> allQuests,
System.Action<string, UnityEngine.Object> addError)
{
var idMap = new Dictionary<string, QuestSO>(StringComparer.Ordinal);
foreach (var q in allQuests)
{
if (string.IsNullOrWhiteSpace(q.questId))
{
addError($"{q.name}: questId 为空,任务无法被系统引用。", q);
continue;
}
if (idMap.TryGetValue(q.questId, out var existing))
addError($"重复 questId \"{q.questId}\"{q.name} 与 {existing.name}", q);
else
idMap[q.questId] = q;
}
return idMap;
}
// 检查 37结构完整性无目标、空引用前置、循环依赖、canFail 配置、好感度配置)
private static void ValidateStructure(
List<QuestSO> allQuests,
Dictionary<string, QuestSO> idMap,
System.Action<string, UnityEngine.Object> addError,
System.Action<string, UnityEngine.Object> addWarn)
{
foreach (var q in allQuests)
{
if (string.IsNullOrWhiteSpace(q.questId)) continue;
if (q.objectives == null || q.objectives.Length == 0)
addWarn($"{q.questId}: objectives 为空,任务无任何目标。", q);
if (q.prerequisiteQuests != null)
foreach (var pre in q.prerequisiteQuests)
if (pre == null) { addWarn($"{q.questId}: prerequisiteQuests 含空引用,请清理 Inspector 中的空槽。", q); break; }
if (HasCircularPrerequisite(q, idMap, new HashSet<string>(StringComparer.Ordinal)))
addError($"{q.questId}: 前置任务链存在循环依赖,将导致任务永远无法变为 Available", q);
if (q.canFail && q.failCondition == null)
addWarn($"{q.questId}: canFail=true 但 failCondition 为空,失败条件永不触发。", q);
if (q.reward != null && q.reward.affinityBonus != 0 && string.IsNullOrEmpty(q.GiverNpcId))
addWarn($"{q.questId}: reward.affinityBonus={q.reward.affinityBonus} 但 GiverNpcId 为空,好感度增量将丢失。", q);
}
}
// 检查 8TriggerZone ↔ ReachAreaObjective markerTag 孤儿交叉检测
private static void ValidateTriggerZones(System.Action<string, UnityEngine.Object> addWarn)
{
var reachTagToSO = new Dictionary<string, BaseGames.Quest.ReachAreaObjective>(StringComparer.Ordinal);
foreach (var obj in AssetOperations.FindAll<BaseGames.Quest.ReachAreaObjective>())
if (!string.IsNullOrEmpty(obj.markerTag))
reachTagToSO[obj.markerTag] = obj;
var triggerTagToPrefab = new Dictionary<string, GameObject>(StringComparer.Ordinal);
foreach (var guid in AssetDatabase.FindAssets("t:Prefab"))
{
var prefabPath = AssetDatabase.GUIDToAssetPath(guid);
var prefabGo = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
if (prefabGo == null) continue;
foreach (var zone in prefabGo.GetComponentsInChildren<BaseGames.World.TriggerZone>(true))
if (!string.IsNullOrEmpty(zone.MarkerTag))
triggerTagToPrefab.TryAdd(zone.MarkerTag, prefabGo);
}
foreach (var (tag, so) in reachTagToSO)
if (!triggerTagToPrefab.ContainsKey(tag))
addWarn($"ReachAreaObjective.markerTag=\"{tag}\" 无对应 Prefab 中的 TriggerZone孤儿目标 Tag。", so);
foreach (var (tag, prefab) in triggerTagToPrefab)
if (!reachTagToSO.ContainsKey(tag))
addWarn($"TriggerZone.markerTag=\"{tag}\" 无对应 ReachAreaObjective孤儿触发器 Tag。", prefab);
}
// 检查 9同任务内 objectiveId 重复
private static void ValidateObjectiveIds(
List<QuestSO> allQuests,
System.Action<string, UnityEngine.Object> addError)
{
foreach (var q in allQuests)
{
if (q.objectives == null || q.objectives.Length == 0) continue;
var seenIds = new HashSet<string>(StringComparer.Ordinal);
foreach (var obj in q.objectives)
{
if (obj == null || string.IsNullOrEmpty(obj.objectiveId)) continue;
if (!seenIds.Add(obj.objectiveId))
addError($"任务 '{q.questId}' 存在重复 objectiveId '{obj.objectiveId}',运行时状态将互串。", q);
}
}
}
// 检查 10branches[i].conditionFlags 含空白字符串
private static void ValidateBranchFlags(
List<QuestSO> allQuests,
System.Action<string, UnityEngine.Object> addWarn)
{
foreach (var q in allQuests)
{
if (q.branches == null || q.branches.Length == 0) continue;
for (int bi = 0; bi < q.branches.Length; bi++)
{
var branch = q.branches[bi];
if (branch.conditionFlags == null || branch.conditionFlags.Length == 0) continue;
for (int fi = 0; fi < branch.conditionFlags.Length; fi++)
if (string.IsNullOrWhiteSpace(branch.conditionFlags[fi]))
addWarn($"任务 '{q.questId}' 分支[{bi}].conditionFlags[{fi}] 为空白字符串,运行时将被跳过,请检查是否遗漏标志名。", q);
}
}
}
// 检查 11reward.itemIds 含空白字符串或无对应 Collectible 预制件
private static void ValidateRewards(
List<QuestSO> allQuests,
System.Action<string, UnityEngine.Object> addWarn)
{
var knownIds = new HashSet<string>(StringComparer.Ordinal);
foreach (var guid in AssetDatabase.FindAssets("t:Prefab"))
{
var prefabPath = AssetDatabase.GUIDToAssetPath(guid);
var go = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
if (go == null) continue;
var col = go.GetComponent<BaseGames.World.Collectible>();
if (col == null) continue;
var so = new UnityEditor.SerializedObject(col);
var idProp = so.FindProperty("_collectibleId") ?? so.FindProperty("collectibleId");
if (idProp != null && !string.IsNullOrEmpty(idProp.stringValue))
knownIds.Add(idProp.stringValue);
}
foreach (var q in allQuests)
{
if (q.reward == null || q.reward.itemIds == null) continue;
for (int ii = 0; ii < q.reward.itemIds.Length; ii++)
{
var itemId = q.reward.itemIds[ii];
if (string.IsNullOrWhiteSpace(itemId))
addWarn($"任务 '{q.questId}' reward.itemIds[{ii}] 为空白字符串,将被跳过。", q);
else if (knownIds.Count > 0 && !knownIds.Contains(itemId))
addWarn($"任务 '{q.questId}' reward.itemIds[{ii}]=\"{itemId}\" 在项目 Prefab 中无对应 Collectible奖励可能无效。", q);
}
}
}
private static bool HasCircularPrerequisite(QuestSO start, Dictionary<string, QuestSO> idMap,
HashSet<string> visited)
{
if (!visited.Add(start.questId)) return true;
if (start.prerequisiteQuests == null) return false;
foreach (var pre in start.prerequisiteQuests)
{
if (pre == null || string.IsNullOrEmpty(pre.questId)) continue;
if (!idMap.TryGetValue(pre.questId, out var preQuest)) continue;
if (HasCircularPrerequisite(preQuest, idMap, visited)) return true;
}
visited.Remove(start.questId);
return false;
}
// ── QuestKeys.cs 常量生成器 ──────────────────────────────────────────
private const string GeneratedFolder = "Assets/_Game/Scripts/Generated";

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cdb78fdcbe3a25f40b0f77d1b42002b9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,171 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace BaseGames.Editor.Modules
{
/// <summary>
/// 批量验证结果窗口:以可滚动列表展示各项配置问题,
/// 每条记录附带"选中"按钮点击后高亮并选中对应资产EditorGUIUtility.PingObject
/// 支持 Error/Warning Tab 切换与文本搜索过滤。
/// 由各验证模块QuestModule、DialogueModule、NpcModule在检测到问题时弹出。
/// </summary>
internal class QuestValidationResultWindow : EditorWindow
{
internal struct Issue
{
public string message;
public bool isError;
public UnityEngine.Object asset; // null = 无对应资产(如孤儿触发器)
}
private List<Issue> _issues;
private int _errorCount;
private int _warnCount;
private int _totalItems;
private string _itemLabel = "资产";
private Vector2 _scroll;
// ── 过滤状态 ─────────────────────────────────────────────────────────
private enum TabMode { All, ErrorsOnly, WarnsOnly }
private TabMode _tab = TabMode.All;
private string _filter = "";
private static readonly GUIStyle s_tabActive = null; // 延迟初始化
private static readonly GUIStyle s_tabInactive = null;
// ── 打开入口 ──────────────────────────────────────────────────────────
internal static void Show(List<Issue> issues, int errorCount, int warnCount, int totalItems, string windowTitle = "批量验证结果", string itemLabel = "资产")
{
var win = GetWindow<QuestValidationResultWindow>(true, windowTitle, true);
win._issues = issues;
win._errorCount = errorCount;
win._warnCount = warnCount;
win._totalItems = totalItems;
win._itemLabel = itemLabel;
win._tab = TabMode.All;
win._filter = "";
win.minSize = new Vector2(560, 380);
win.Show();
}
// ── 绘制 ──────────────────────────────────────────────────────────────
private void OnGUI()
{
if (_issues == null) { EditorGUILayout.LabelField("无数据。"); return; }
bool clean = _errorCount == 0 && _warnCount == 0;
// ── 标题摘要 ──
EditorGUILayout.Space(6);
var summaryStyle = new GUIStyle(EditorStyles.boldLabel) { fontSize = 12 };
if (clean) summaryStyle.normal.textColor = new Color(0.2f, 0.75f, 0.2f);
string prefix = clean ? "✅ " : (_errorCount > 0 ? "❌ " : "⚠ ");
string summary = $"{prefix}验证完成:{_totalItems} 个{_itemLabel} · {_errorCount} 个错误 · {_warnCount} 个警告";
EditorGUILayout.LabelField(summary, summaryStyle);
EditorGUILayout.Space(4);
if (clean)
{
EditorGUILayout.LabelField($"所有 {_itemLabel} 配置均合法!", EditorStyles.centeredGreyMiniLabel);
return;
}
// ── 分隔线 ──
var divRect = EditorGUILayout.GetControlRect(false, 1);
EditorGUI.DrawRect(divRect, new Color(0.35f, 0.35f, 0.35f));
EditorGUILayout.Space(4);
// ── Tab 切换 + 搜索框 ──
EditorGUILayout.BeginHorizontal();
DrawTab("全部", TabMode.All, _issues.Count);
DrawTab("错误", TabMode.ErrorsOnly, _errorCount);
DrawTab("警告", TabMode.WarnsOnly, _warnCount);
GUILayout.FlexibleSpace();
GUILayout.Label("🔍", GUILayout.Width(18));
_filter = EditorGUILayout.TextField(_filter, GUILayout.Width(180));
if (GUILayout.Button("×", GUILayout.Width(22))) _filter = "";
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space(4);
// ── 问题列表 ──
_scroll = EditorGUILayout.BeginScrollView(_scroll);
int shown = 0;
foreach (var issue in _issues)
{
if (!MatchesFilter(issue)) continue;
shown++;
DrawIssueRow(issue);
EditorGUILayout.Space(2);
}
if (shown == 0)
EditorGUILayout.LabelField("(当前过滤条件下无结果)", EditorStyles.centeredGreyMiniLabel);
EditorGUILayout.EndScrollView();
// ── 底部状态栏 ──
EditorGUILayout.Space(2);
var statusRect = EditorGUILayout.GetControlRect(false, 1);
EditorGUI.DrawRect(statusRect, new Color(0.3f, 0.3f, 0.3f));
EditorGUILayout.LabelField(
$"显示 {shown} / {_issues.Count} 条",
EditorStyles.centeredGreyMiniLabel);
}
// ── 辅助方法 ─────────────────────────────────────────────────────────
private bool MatchesFilter(Issue issue)
{
if (_tab == TabMode.ErrorsOnly && !issue.isError) return false;
if (_tab == TabMode.WarnsOnly && issue.isError) return false;
if (!string.IsNullOrEmpty(_filter))
{
bool msgMatch = issue.message.Contains(_filter, System.StringComparison.OrdinalIgnoreCase);
bool assetMatch = issue.asset != null &&
issue.asset.name.Contains(_filter, System.StringComparison.OrdinalIgnoreCase);
if (!msgMatch && !assetMatch) return false;
}
return true;
}
private void DrawTab(string label, TabMode mode, int count)
{
bool active = _tab == mode;
var style = active
? new GUIStyle(EditorStyles.miniButtonMid) { fontStyle = FontStyle.Bold }
: EditorStyles.miniButtonMid;
if (active) style.normal.textColor = new Color(0.4f, 0.8f, 1f);
string text = $"{label} ({count})";
if (GUILayout.Button(text, style, GUILayout.MinWidth(72)))
_tab = mode;
}
private static void DrawIssueRow(Issue issue)
{
EditorGUILayout.BeginHorizontal(EditorStyles.helpBox);
// 图标
var iconContent = issue.isError
? EditorGUIUtility.IconContent("console.erroricon.sml")
: EditorGUIUtility.IconContent("console.warnicon.sml");
GUILayout.Label(iconContent, GUILayout.Width(20), GUILayout.Height(18));
// 消息文字
EditorGUILayout.LabelField(issue.message, EditorStyles.wordWrappedLabel);
// 定位按钮(有资产引用时显示)
if (issue.asset != null)
{
if (GUILayout.Button("选中", GUILayout.Width(40), GUILayout.Height(18)))
{
EditorGUIUtility.PingObject(issue.asset);
Selection.activeObject = issue.asset;
}
}
EditorGUILayout.EndHorizontal();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cd040e3f82e3b3040a92fac14502ef4a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -10,7 +10,7 @@ namespace BaseGames.Editor.Modules
/// <summary>
/// DataHub 技能模块 —— 管理 FormSkillSO 资产。
/// </summary>
public class SkillModule : IDataModule
public class SkillModule : IDataModule, IDataModuleOrdered
{
private const string Folder = "Assets/_Game/Data/Skills";
private const string Prefix = "SKL_";
@@ -18,6 +18,7 @@ namespace BaseGames.Editor.Modules
public string ModuleId => "skill";
public string DisplayName => "技能";
public string IconName => null;
public int DisplayOrder => 20;
private SoListPane<FormSkillSO> _listPane;
private DetailHeader _header;
@@ -193,16 +194,24 @@ namespace BaseGames.Editor.Modules
T asset,
string folder,
string prefix,
Action<T> onCreated,
Action<T> onCloned,
Action onDeleted) where T : UnityEngine.ScriptableObject
Action<T> onCreated,
Action<T> onCloned,
Action onDeleted,
Action<Action<T>> wizardCreate = null) where T : UnityEngine.ScriptableObject
{
var bar = MakeActionBar();
new Button(() =>
{
var c = AssetOperations.Create<T>(folder, prefix + "New");
if (c != null) onCreated?.Invoke(c);
if (wizardCreate != null)
{
wizardCreate(c => onCreated?.Invoke(c));
}
else
{
var c = AssetOperations.Create<T>(folder, prefix + "New");
if (c != null) onCreated?.Invoke(c);
}
}) { text = "新建" }.AlsoAddTo(bar);
new Button(() =>

View File

@@ -10,7 +10,7 @@ namespace BaseGames.Editor.Modules
/// <summary>
/// DataHub 流式加载模块 —— 管理 <see cref="StreamingBudgetConfigSO"/> 资产。
/// </summary>
public class StreamingModule : IDataModule
public class StreamingModule : IDataModule, IDataModuleOrdered
{
private const string Folder = "Assets/_Game/Data/Streaming";
private const string Prefix = "STR_";
@@ -18,6 +18,7 @@ namespace BaseGames.Editor.Modules
public string ModuleId => "streaming";
public string DisplayName => "流式加载";
public string IconName => "d_RectTransformBlueprint";
public int DisplayOrder => 70;
private SoListPane<StreamingBudgetConfigSO> _listPane;
private DetailHeader _header;

View File

@@ -10,7 +10,7 @@ namespace BaseGames.Editor.Modules
/// <summary>
/// DataHub 武器模块 —— 管理 WeaponSO 资产。
/// </summary>
public class WeaponModule : IDataModule
public class WeaponModule : IDataModule, IDataModuleOrdered
{
private const string Folder = "Assets/_Game/Data/Weapons";
private const string Prefix = "WPN_";
@@ -18,6 +18,7 @@ namespace BaseGames.Editor.Modules
public string ModuleId => "weapon";
public string DisplayName => "武器";
public string IconName => null;
public int DisplayOrder => 10;
private SoListPane<WeaponSO> _listPane;
private DetailHeader _header;

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ba51d204b9cde834f9a521996715f883
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 832e6ad6d64454d4286183c6d7cfdc3e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,118 @@
using UnityEditor;
using UnityEngine;
using BaseGames.Quest;
using BaseGames.Core;
namespace BaseGames.Editor.Quest
{
/// <summary>
/// QuestSO 自定义 Inspector。
/// 在检测到旧版前置字段prerequisiteQuests / prerequisiteFlags有数据时
/// 显示迁移提示框和一键迁移按钮,引导策划将数据迁移到 QuestPrerequisite 统一结构。
/// </summary>
[CustomEditor(typeof(QuestSO))]
public class QuestSOEditor : UnityEditor.Editor
{
private bool _showMigrationBox = true;
public override void OnInspectorGUI()
{
serializedObject.Update();
var quest = (QuestSO)target;
// ── 旧版字段迁移提示 ──────────────────────────────────────────────
#pragma warning disable CS0618
bool hasLegacyQuests = quest.prerequisiteQuests != null && quest.prerequisiteQuests.Length > 0;
bool hasLegacyFlags = quest.prerequisiteFlags != null && quest.prerequisiteFlags.Length > 0;
#pragma warning restore CS0618
if (hasLegacyQuests || hasLegacyFlags)
{
_showMigrationBox = EditorGUILayout.BeginFoldoutHeaderGroup(_showMigrationBox, "⚠ 旧版前置字段迁移");
if (_showMigrationBox)
{
EditorGUILayout.HelpBox(
"检测到旧版前置字段有数据:\n" +
(hasLegacyQuests ? $" • prerequisiteQuests{quest.prerequisiteQuests.Length} 项\n" : "") +
(hasLegacyFlags ? $" • prerequisiteFlags{quest.prerequisiteFlags.Length} 项\n" : "") +
"\n新版 'prerequisites'QuestPrerequisite字段已支持更完整的前置配置。\n" +
"点击下方按钮可将旧版数据自动迁移至新字段,迁移后旧字段将被清空。\n" +
"迁移操作可撤销Ctrl+Z。",
MessageType.Warning);
bool hasNewData = quest.prerequisites.HasAny;
if (hasNewData)
EditorGUILayout.HelpBox(
"新版 prerequisites 字段已有数据。点击迁移将与旧版数据合并(去重),不会覆盖现有配置。",
MessageType.Info);
if (GUILayout.Button("一键迁移旧版前置字段 → prerequisites"))
{
MigrateLegacyPrerequisites(quest);
}
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space(4);
}
// ── 默认 Inspector ────────────────────────────────────────────────
DrawDefaultInspector();
serializedObject.ApplyModifiedProperties();
}
private static void MigrateLegacyPrerequisites(QuestSO quest)
{
Undo.RecordObject(quest, "迁移 QuestSO 旧版前置字段");
#pragma warning disable CS0618
int legacyQuestCount = quest.prerequisiteQuests?.Length ?? 0;
int legacyFlagCount = quest.prerequisiteFlags?.Length ?? 0;
// 迁移 prerequisiteQuests → prerequisites.questDependencies合并去重
if (quest.prerequisiteQuests != null && quest.prerequisiteQuests.Length > 0)
{
var existing = quest.prerequisites.questDependencies ?? System.Array.Empty<QuestSO>();
var merged = new System.Collections.Generic.HashSet<QuestSO>(existing);
foreach (var q in quest.prerequisiteQuests)
if (q != null) merged.Add(q);
quest.prerequisites.questDependencies = new QuestSO[merged.Count];
merged.CopyTo(quest.prerequisites.questDependencies);
quest.prerequisiteQuests = System.Array.Empty<QuestSO>();
}
// 迁移 prerequisiteFlags → prerequisites.flagCondition合并去重
if (quest.prerequisiteFlags != null && quest.prerequisiteFlags.Length > 0)
{
var existing = quest.prerequisites.flagCondition.flags ?? System.Array.Empty<string>();
var merged = new System.Collections.Generic.HashSet<string>(
existing, System.StringComparer.Ordinal);
foreach (var f in quest.prerequisiteFlags)
if (!string.IsNullOrEmpty(f)) merged.Add(f);
quest.prerequisites.flagCondition.flags = new string[merged.Count];
merged.CopyTo(quest.prerequisites.flagCondition.flags);
// 迁移逻辑模式(旧字段覆盖新字段,以旧配置为准)
quest.prerequisites.flagCondition.logic = quest.prerequisiteFlagsLogic;
quest.prerequisiteFlags = System.Array.Empty<string>();
quest.prerequisiteFlagsLogic = WorldStateFlagLogic.And;
}
#pragma warning restore CS0618
EditorUtility.SetDirty(quest);
AssetDatabase.SaveAssets();
Debug.Log($"[QuestSOEditor] '{quest.name}' 旧版前置字段迁移完成(任务:{legacyQuestCount} 项,标志:{legacyFlagCount} 项)。", quest);
EditorUtility.DisplayDialog(
"迁移完成",
$"任务 \"{quest.name}\" 旧版前置字段已成功迁移:\n\n" +
$" 前置任务:{legacyQuestCount} 项 → prerequisites.questDependencies\n" +
$" 前置标志:{legacyFlagCount} 项 → prerequisites.flagCondition.flags\n\n" +
"旧版字段已清空。操作可通过 Ctrl+Z 撤销。",
"确定");
}
}
}

View File

@@ -0,0 +1,161 @@
using System;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace BaseGames.Editor.Shared
{
/// <summary>
/// 资产快速创建向导 —— 弹出式 EditorWindow引导输入 ID 并预览文件名,
/// 一键创建 ScriptableObject 到指定文件夹。
/// 用法: AssetCreationWizard.Show&lt;QuestSO&gt;(folder, prefix, (asset, id) => { asset.questId = id; });
/// </summary>
public class AssetCreationWizard : EditorWindow
{
private string _folder;
private string _prefix;
private string _idInput = "";
private string _typeName;
private Type _assetType;
private Action<ScriptableObject, string> _onCreated;
private TextField _idField;
private Label _previewLabel;
// ── 公开入口 ─────────────────────────────────────────────────────────
/// <summary>
/// 打开向导。资产创建完成后以 (asset, id) 形式回调,调用方可在回调中自行设置 ID 字段。
/// </summary>
public static void Show<T>(string folder, string prefix, Action<T, string> onCreated)
where T : ScriptableObject
{
string displayName = typeof(T).Name.EndsWith("SO")
? typeof(T).Name[..^2]
: typeof(T).Name;
var win = CreateInstance<AssetCreationWizard>();
win.titleContent = new GUIContent($"新建 {displayName}");
win._folder = folder;
win._prefix = prefix;
win._assetType = typeof(T);
win._typeName = displayName;
win._onCreated = (so, id) => onCreated((T)so, id);
win.minSize = new Vector2(320, 132);
win.maxSize = new Vector2(480, 132);
win.ShowUtility();
}
// ── UI 构建 ──────────────────────────────────────────────────────────
private void CreateGUI()
{
var root = rootVisualElement;
root.style.paddingTop = 12;
root.style.paddingBottom = 12;
root.style.paddingLeft = 16;
root.style.paddingRight = 16;
// 说明行
var desc = new Label($"将在 {_folder} 中新建一个 {_typeName}");
desc.style.fontSize = 10;
desc.style.opacity = 0.55f;
desc.style.marginBottom = 10;
root.Add(desc);
// ID 输入行
var row = new VisualElement();
row.style.flexDirection = FlexDirection.Row;
row.style.alignItems = Align.Center;
row.style.marginBottom = 6;
var idLabel = new Label("ID");
idLabel.style.width = 36;
idLabel.style.unityTextAlign = TextAnchor.MiddleLeft;
idLabel.style.flexShrink = 0;
row.Add(idLabel);
_idField = new TextField { value = "" };
_idField.style.flexGrow = 1;
_idField.RegisterValueChangedCallback(evt =>
{
_idInput = evt.newValue;
RefreshPreview();
});
row.Add(_idField);
root.Add(row);
// 文件名预览
_previewLabel = new Label("文件名:(请输入 ID");
_previewLabel.style.fontSize = 10;
_previewLabel.style.opacity = 0.5f;
_previewLabel.style.marginBottom = 12;
root.Add(_previewLabel);
// 按钮行
var btnRow = new VisualElement();
btnRow.style.flexDirection = FlexDirection.Row;
btnRow.style.justifyContent = Justify.FlexEnd;
var cancelBtn = new Button(Close) { text = "取消" };
cancelBtn.style.width = 56;
cancelBtn.style.marginRight = 6;
btnRow.Add(cancelBtn);
var createBtn = new Button(DoCreate) { text = "创建" };
createBtn.style.width = 56;
btnRow.Add(createBtn);
root.Add(btnRow);
// 自动聚焦 ID 输入框
_idField.schedule.Execute(() => _idField.Focus()).StartingIn(50);
}
// ── 私有逻辑 ─────────────────────────────────────────────────────────
private void RefreshPreview()
{
if (_previewLabel == null) return;
_previewLabel.text = string.IsNullOrWhiteSpace(_idInput)
? "文件名:(请输入 ID"
: $"文件名:{_prefix}{_idInput}.asset";
}
private void DoCreate()
{
if (string.IsNullOrWhiteSpace(_idInput))
{
EditorUtility.DisplayDialog("ID 不能为空", "请输入有效的 ID 后再创建。", "确定");
return;
}
if (!Regex.IsMatch(_idInput, @"^[\w\-]+$"))
{
EditorUtility.DisplayDialog("ID 格式有误", "ID 只能包含字母、数字、下划线或连字符。", "确定");
return;
}
if (!Directory.Exists(_folder))
Directory.CreateDirectory(_folder);
string path = $"{_folder}/{_prefix}{_idInput}.asset";
if (File.Exists(path))
{
EditorUtility.DisplayDialog("文件已存在", $"路径已存在:\n{path}\n请更换 ID。", "确定");
return;
}
var asset = CreateInstance(_assetType) as ScriptableObject;
AssetDatabase.CreateAsset(asset, path);
Undo.RegisterCreatedObjectUndo(asset, $"创建 {_typeName} {_idInput}");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
_onCreated?.Invoke(asset, _idInput);
Close();
}
}
}

View File

@@ -16,6 +16,29 @@ namespace BaseGames.Editor
// ── 事件(使用字段委托,允许外部直接赋值替换,避免累积)─────────────
public Action<T> SelectionChanged;
/// <summary>
/// 附加过滤条件(可选)。返回 true = 保留;返回 false = 过滤掉。
/// 赋值后调用 <see cref="ApplyFilter()"/> 使其生效;置 null 时仅按文本搜索过滤。
/// </summary>
public Func<T, bool> ExtraFilter
{
get => _extraFilter;
set { _extraFilter = value; ApplyFilter(); }
}
private Func<T, bool> _extraFilter;
/// <summary>
/// 扩展搜索文本提供器(可选)。返回除资产名以外也纳入搜索的附加文本(如 ID、本地化 Key 等)。
/// 搜索时将对 "资产名 + 返回值" 拼接文本做不区分大小写的包含匹配。
/// 赋值后立即重新应用过滤。
/// </summary>
public Func<T, string> GetExtraSearchText
{
get => _getExtraSearchText;
set { _getExtraSearchText = value; ApplyFilter(); }
}
private Func<T, string> _getExtraSearchText;
// ── 字段 ─────────────────────────────────────────────────────────────
private readonly string _defaultFolder;
private readonly string _defaultPrefix;
@@ -205,9 +228,25 @@ namespace BaseGames.Editor
_filtered.Clear();
foreach (var item in _all)
{
if (string.IsNullOrEmpty(_search) ||
item.name.IndexOf(_search, StringComparison.OrdinalIgnoreCase) >= 0)
_filtered.Add(item);
bool nameMatch;
if (string.IsNullOrEmpty(_search))
{
nameMatch = true;
}
else
{
nameMatch = item.name.IndexOf(_search, StringComparison.OrdinalIgnoreCase) >= 0;
if (!nameMatch && _getExtraSearchText != null)
{
var extra = _getExtraSearchText(item);
if (!string.IsNullOrEmpty(extra))
nameMatch = extra.IndexOf(_search, StringComparison.OrdinalIgnoreCase) >= 0;
}
}
if (!nameMatch) continue;
if (_extraFilter != null && !_extraFilter(item)) continue;
_filtered.Add(item);
}
}
_listView.RefreshItems();