using Ichni.Story.Dialogue; using Ichni.Story.UI; using UnityEngine; using UnityEngine.Localization.Settings; using Yarn.Unity; namespace Ichni.Story.YarnFunctions { /// /// 包含与故事树节点控制、全局进程、存档交互相关的 Yarn 自定义命令注册器。 /// public static class StoryTreeCommands { // ── Yarn Commands ──────────────────────────────────────────────────────── /// /// 解锁一首新歌曲,并在当前这段对话结束(对话 UI 淡出)后,弹出 MessageBox 提示。 /// 格式: <<unlock_song songUnlockKey>> /// /// 要解锁的歌曲密钥/ID [YarnCommand("unlock_song")] public static void UnlockSong(string songUnlockKey) { if (GameSaveManager.instance == null || GameSaveManager.instance.SongSaveModule == null) { Debug.LogError("[StoryTreeCommands] 无法解锁歌曲:GameSaveManager 或其 SongSaveModule 未初始化!"); return; } // 1. 检查是否已经解锁 if (GameSaveManager.instance.SongSaveModule.CheckStoryKey(songUnlockKey)) { Debug.Log($"[StoryTreeCommands] 歌曲 {songUnlockKey} 已处于解锁状态。"); return; } // 2. 写入解锁状态并保存存档 GameSaveManager.instance.SongSaveModule.storyUnlockKeys.Add(songUnlockKey); GameSaveManager.instance.SongSaveModule.SaveStoryUnlockKeys(); Debug.Log($"[StoryTreeCommands] 已成功写入并保存歌曲解锁密钥:{songUnlockKey}"); // 3. 将 UI 弹窗提示加入到对话结束队列中 if (StoryDialogueController.instance != null) { StoryDialogueController.instance.dialogueEndActions.Add(() => { if (StoryMessageBoxUIPage.instance != null) { StoryMessageBoxUIPage.instance.ShowUnlockMessage(songUnlockKey); } else { Debug.LogError("[StoryTreeCommands] 弹窗失败:场景中未找到 StoryMessageBoxUIPage 实例!"); } }); } else { Debug.LogError("[StoryTreeCommands] 弹窗队列注册失败:未找到 StoryDialogueController 实例!"); } } /// /// 在对话结束后,弹出一个自定义 MessageBox 提示。 /// 会尝试使用 Unity Localization 进行翻译,如果找不到对应条目则回退显示原文本(Key)。 /// 格式: <<show_message titleKey contentKey [tableName]>> /// /// 标题文本或本地化键 /// 正文文本或本地化键 /// Unity Localization 中的 String Table 名称 [YarnCommand("show_message")] public static void ShowMessage(string titleKey, string contentKey, string tableName = "Message") { string translatedTitle = GetTranslatedText(tableName, titleKey); string translatedContent = GetTranslatedText(tableName, contentKey); Debug.Log($"[StoryTreeCommands] 准备在对话结束后显示自定义弹窗:标题='{translatedTitle}',内容='{translatedContent}'"); StoryDialogueController.instance.dialogueEndActions.Add(() => { StoryMessageBoxUIPage.instance.ShowCustomMessage(translatedTitle, translatedContent); }); } // ── 内部辅助 ───────────────────────────────────────────────────────────── private static string GetTranslatedText(string tableName, string key) { if (string.IsNullOrEmpty(key)) return string.Empty; try { // 尝试从 Unity Localization 中获取翻译文本 string translated = LocalizationSettings.StringDatabase.GetLocalizedString(tableName, key); // 若获取失败或为空,则直接原样返回 key 作为兜底文本 return string.IsNullOrEmpty(translated) ? key : translated; } catch { // 如果表不存在或其他异常,返回原 key return key; } } } }