```csharp using UnityEngine; using System.Collections.Generic; using System.IO; using TMPro; using UnityEditor.Search; #if UNITY_EDITOR using UnityEditor; #endif [RequireComponent(typeof(AudioSource))] [RequireComponent(typeof(CircleCollider2D))] public class NPCConversationManager : MonoBehaviour { [System.Serializable] public class Conversation { public string conversationName; public GameObject dialogueRoot; [SerializeField] public GameObject startingNode; public string jsonFile; [SerializeField] public List<TimeSinceStartCondition> timeConditions = new List<TimeSinceStartCondition>(); [SerializeField] public List<MemoryCondition> memoryConditions = new List<MemoryCondition>(); [SerializeField] public List<RandomChanceCondition> randomConditions = new List<RandomChanceCondition>(); public DialogueNodeAuthoring StartingNode => startingNode != null ? startingNode.GetComponent<DialogueNodeAuthoring>() : null; } [SerializeField] private string NPCName; [SerializeField] private int conversationToExportIndex = 0; [SerializeField] private List<Conversation> conversations = new List<Conversation>(); [SerializeField] private GameObject defaultDialogueRoot; [SerializeField] private GameObject defaultStartingNode; [SerializeField] private NPCMemory npcMemoryComponent; // Assign in Inspector or find in hierarchy [SerializeField] private GameObject interactionPromptUI; // Assign the Text UI object here [SerializeField] private float uiTimeout = 3f; // Time in seconds before UI disappears private DialogueManager dialogueManager; private bool playerInRange = false; private float uiTimer = 0f; private bool isConversationActive = false; // Track if a conversation is ongoing [SerializeField] private KeyCode testKey = KeyCode.T; void Start() { dialogueManager = DialogueManager.Instance; if (dialogueManager == null && DialogueManager.debugEnabled) Debug.LogError("No DialogueManager instance found in scene!"); if (npcMemoryComponent == null) { npcMemoryComponent = GetComponent<NPCMemory>(); if (npcMemoryComponent == null && DialogueManager.debugEnabled) Debug.LogWarning("No NPCMemory component found on this GameObject!"); else if (DialogueManager.debugEnabled) Debug.Log("NPCMemory component auto-assigned."); } if (interactionPromptUI == null && DialogueManager.debugEnabled) Debug.LogWarning("InteractionPromptUI not assigned!"); else interactionPromptUI.SetActive(false); // Ensure UI is hidden at start // Ensure the collider is a trigger CircleCollider2D collider = GetComponent<CircleCollider2D>(); if (collider != null) collider.isTrigger = true; } void Update() { if (playerInRange) { if (Input.GetKeyDown(testKey)) { InitiateConversation(); HidePrompt(); isConversationActive = true; // Mark conversation as active } else if (interactionPromptUI.activeSelf) { uiTimer -= Time.deltaTime; if (uiTimer <= 0f) { HidePrompt(); } } } } void OnTriggerEnter2D(Collider2D other) // Changed to 2D { if (other.CompareTag("Player")) { playerInRange = true; ShowPrompt(); if (DialogueManager.debugEnabled) Debug.Log("Player entered NPC range (2D)."); } } void OnTriggerExit2D(Collider2D other) // Changed to 2D { if (other.CompareTag("Player")) { playerInRange = false; HidePrompt(); if (isConversationActive && dialogueManager != null) { dialogueManager.EndDialogue(); // Close the conversation isConversationActive = false; if (DialogueManager.debugEnabled) Debug.Log("Player walked away, ending conversation."); } if (DialogueManager.debugEnabled) Debug.Log("Player exited NPC range (2D)."); } } private void ShowPrompt() { if (interactionPromptUI != null) { interactionPromptUI.GetComponent<TMP_Text>().text=("Press "+testKey+" to Talk to "+NPCName+"."); interactionPromptUI.SetActive(true); uiTimer = uiTimeout; } } private void HidePrompt() { if (interactionPromptUI != null) { interactionPromptUI.SetActive(false); } } public void InitiateConversation() { if (dialogueManager == null) { if (DialogueManager.debugEnabled) Debug.LogError("DialogueManager not found!"); return; } Conversation selectedConversation = SelectConversation(); if (selectedConversation != null) { dialogueManager.npcDialogueAudioSource = gameObject.GetComponent<AudioSource>(); dialogueManager.currentNPC = this; // Set the direct reference if (dialogueManager.npcDialogueAudioSource == null && DialogueManager.debugEnabled) Debug.LogError(quot;No AudioSource found on {gameObject.name} for dialogue playback!"); if (!string.IsNullOrEmpty(selectedConversation.jsonFile)) { string jsonFileName = selectedConversation.jsonFile.EndsWith(".json") ? selectedConversation.jsonFile.Substring(0, selectedConversation.jsonFile.Length - 5) : selectedConversation.jsonFile; dialogueManager.LoadDialogueFromFile(jsonFileName); dialogueManager.StartDialogue("Start"); } else if (selectedConversation.dialogueRoot != null && selectedConversation.StartingNode != null) { dialogueManager.LoadDialogueFromGameObjects(selectedConversation.dialogueRoot); dialogueManager.StartDialogue(selectedConversation.StartingNode); } if (DialogueManager.debugEnabled) Debug.Log(quot;Starting conversation: {selectedConversation.conversationName}"); } else if (defaultDialogueRoot != null && defaultStartingNode != null) { dialogueManager.npcDialogueAudioSource = gameObject.GetComponent<AudioSource>(); dialogueManager.currentNPC = this; // Set the direct reference if (dialogueManager.npcDialogueAudioSource == null && DialogueManager.debugEnabled) Debug.LogError(quot;No AudioSource found on {gameObject.name} for default dialogue playback!"); dialogueManager.LoadDialogueFromGameObjects(defaultDialogueRoot); dialogueManager.StartDialogue(defaultStartingNode.GetComponent<DialogueNodeAuthoring>()); if (DialogueManager.debugEnabled) Debug.Log("Starting default conversation."); } else { if (DialogueManager.debugEnabled) Debug.LogWarning("No valid conversation or default set!"); } } private Conversation SelectConversation() { foreach (Conversation convo in conversations) { if ((string.IsNullOrEmpty(convo.jsonFile) && (convo.dialogueRoot == null || convo.StartingNode == null)) || (!string.IsNullOrEmpty(convo.jsonFile) && convo.dialogueRoot != null)) { if (DialogueManager.debugEnabled) Debug.LogWarning(quot;Conversation '{convo.conversationName}' has invalid setup: JSON and GameObject mix or missing required fields!"); continue; } bool allConditionsMet = true; foreach (var condition in convo.timeConditions) { if (!condition.IsMet(this)) { allConditionsMet = false; break; } } if (allConditionsMet) { foreach (var condition in convo.memoryConditions) { bool met = condition.IsMet(this); if (DialogueManager.debugEnabled) Debug.Log(quot;MemoryCondition {condition.memoryKey} = {GetMemory(condition.memoryKey)} vs Required {condition.requiredValue}: {met}"); if (!met) { allConditionsMet = false; break; } } } if (allConditionsMet) { foreach (var condition in convo.randomConditions) { if (!condition.IsMet(this)) { allConditionsMet = false; break; } } } if (allConditionsMet) { return convo; } } return null; } // Update memory methods public void SetMemory(string key, bool value) { if (npcMemoryComponent != null) { npcMemoryComponent.SetMemory(key, value); } else if (DialogueManager.debugEnabled) Debug.LogWarning("Cannot set memory: NPCMemory component not assigned!"); } public bool GetMemory(string key, bool defaultValue = false) { return npcMemoryComponent != null ? npcMemoryComponent.GetMemory(key, defaultValue) : defaultValue; } #if UNITY_EDITOR [ContextMenu("Export Selected Conversation to JSON")] public void ExportSelectedConversationToJson() { if (conversations.Count == 0) { if (DialogueManager.debugEnabled) Debug.LogWarning("No conversations to export!"); return; } if (conversationToExportIndex < 0 || conversationToExportIndex >= conversations.Count) { if (DialogueManager.debugEnabled) Debug.LogWarning(quot;Invalid conversation index {conversationToExportIndex}—must be between 0 and {conversations.Count - 1}!"); return; } string baseFolder = "Assets/Resources/Conversations"; string npcFolder = quot;{baseFolder}/{gameObject.name}"; if (!Directory.Exists(baseFolder)) { Directory.CreateDirectory(baseFolder); } if (!Directory.Exists(npcFolder)) { Directory.CreateDirectory(npcFolder); AssetDatabase.Refresh(); } ExportConversationToJson(conversationToExportIndex, npcFolder); } [ContextMenu("Export All Conversations to JSON")] public void ExportAllConversationsToJson() { if (conversations.Count == 0) { if (DialogueManager.debugEnabled) Debug.LogWarning("No conversations to export!"); return; } string baseFolder = "Assets/Resources/Conversations"; string npcFolder = quot;{baseFolder}/{gameObject.name}"; if (!Directory.Exists(baseFolder)) { Directory.CreateDirectory(baseFolder); } if (!Directory.Exists(npcFolder)) { Directory.CreateDirectory(npcFolder); AssetDatabase.Refresh(); } for (int i = 0; i < conversations.Count; i++) { ExportConversationToJson(i, npcFolder); } if (DialogueManager.debugEnabled) Debug.Log(quot;Exported all {conversations.Count} conversations to {npcFolder}"); } private void ExportConversationToJson(int index, string folder) { Conversation convo = conversations[index]; if (string.IsNullOrEmpty(convo.jsonFile) && (convo.dialogueRoot == null || convo.StartingNode == null)) { if (DialogueManager.debugEnabled) Debug.LogWarning(quot;Conversation '{convo.conversationName}' has no valid JSON file or GameObject setup to export!"); return; } if (!string.IsNullOrEmpty(convo.jsonFile)) { if (DialogueManager.debugEnabled) Debug.Log(quot;Conversation '{convo.conversationName}' already has a JSON file assigned: {convo.jsonFile}"); return; } DialogueManager.DialogueData data = new DialogueManager.DialogueData { environment = new DialogueManager.EnvironmentData(), nodes = new List<DialogueManager.DialogueNode>(), memory = npcMemoryComponent != null ? npcMemoryComponent.GetMemoryList() : new List<MemoryEntry>() // Add memory to JSON }; Environment env = convo.dialogueRoot.GetComponent<Environment>(); if (env != null) { data.environment.environmentImagePath = EnsureAssetInResources(env.EnvironmentImage, "environment"); data.environment.ambientAudioPath = EnsureAssetInResources(env.AmbientAudio, "environment"); } else if (DialogueManager.debugEnabled) Debug.LogWarning(quot;No Environment component on {convo.dialogueRoot.name}—exporting without environment data."); DialogueNodeAuthoring[] nodes = convo.dialogueRoot.GetComponentsInChildren<DialogueNodeAuthoring>(); foreach (DialogueNodeAuthoring node in nodes) { string spritePath = EnsureAssetInResources(node.characterSprite, "characterSprite"); string audioPath = EnsureAssetInResources(node.audioToPlay, "audioToPlay"); string animPath = EnsureAssetInResources(node.animationToPlay, "animationToPlay"); string playerSpritePath = EnsureAssetInResources(node.playerSprite, "playerSprite"); DialogueManager.DialogueNode jsonNode = new DialogueManager.DialogueNode { id = node.Id, characterName = node.characterName, characterSpritePath = spritePath, emotionalState = node.emotionalState, dialogueText = node.dialogueText, choices = new List<DialogueManager.DialogueNode.Choice>(), audioToPlayPath = audioPath, animationToPlayPath = animPath, characterPanelColor = node.characterPanelColor, dialoguePanelColor = node.dialoguePanelColor, textColor = node.textColor, linearNextNodeId = node.linearNextNode != null ? node.linearNextNode.Id : "", // Player fields playerName = node.playerName, playerSpritePath = playerSpritePath, playerEmotionalState = node.playerEmotionalState, isPlayerSpeaking = node.isPlayerSpeaking }; foreach (var choice in node.Choices) { jsonNode.choices.Add(new DialogueManager.DialogueNode.Choice { choiceText = choice.choiceText, nextNodeId = choice.nextNode != null ? choice.nextNode.Id : "", memoryKey = choice.memoryKey, // Add this memoryValue = choice.memoryValue // Add this }); } data.nodes.Add(jsonNode); } string json = JsonUtility.ToJson(data, true); string path = quot;{folder}/{convo.conversationName}.json"; File.WriteAllText(path, json); AssetDatabase.Refresh(); if (DialogueManager.debugEnabled) Debug.Log(quot;Exported conversation '{convo.conversationName}' to {path}"); string relativePath = path.Replace("Assets/Resources/", "").Replace(".json", ""); convo.jsonFile = relativePath; EditorUtility.SetDirty(this); } [ContextMenu("Import Conversation from JSON")] public void ImportConversationFromJson() { string path = EditorUtility.OpenFilePanel("Import JSON Conversation", "Assets/Resources/Conversations", "json"); if (string.IsNullOrEmpty(path)) { return; } string json = File.ReadAllText(path); DialogueManager.DialogueData data = JsonUtility.FromJson<DialogueManager.DialogueData>(json); if (data == null || data.nodes == null || data.nodes.Count == 0) { if (DialogueManager.debugEnabled) Debug.LogWarning(quot;Invalid or empty JSON file at {path}!"); return; } string fileName = Path.GetFileNameWithoutExtension(path); string npcName = gameObject.name; GameObject npcRoot = gameObject; GameObject dialogueRoot = new GameObject(fileName); dialogueRoot.transform.SetParent(npcRoot.transform, false); Undo.RegisterCreatedObjectUndo(dialogueRoot, "Import Conversation"); NPCMemory memoryComponent = dialogueRoot.AddComponent<NPCMemory>(); if (data.memory != null) { memoryComponent.SetMemoryList(data.memory); } Environment env = dialogueRoot.AddComponent<Environment>(); if (data.environment != null) { env.environmentImage = string.IsNullOrEmpty(data.environment.environmentImagePath) ? null : Resources.Load<Sprite>(data.environment.environmentImagePath); env.ambientAudio = string.IsNullOrEmpty(data.environment.ambientAudioPath) ? null : Resources.Load<AudioClip>(data.environment.ambientAudioPath); } Dictionary<string, DialogueNodeAuthoring> nodeMap = new Dictionary<string, DialogueNodeAuthoring>(); foreach (DialogueManager.DialogueNode jsonNode in data.nodes) { GameObject nodeObj = new GameObject(jsonNode.id); nodeObj.transform.SetParent(dialogueRoot.transform, false); DialogueNodeAuthoring node = nodeObj.AddComponent<DialogueNodeAuthoring>(); Undo.RegisterCreatedObjectUndo(nodeObj, "Import Node"); node.characterName = jsonNode.characterName; node.characterSprite = string.IsNullOrEmpty(jsonNode.characterSpritePath) ? null : Resources.Load<Sprite>(jsonNode.characterSpritePath); node.emotionalState = jsonNode.emotionalState; node.dialogueText = jsonNode.dialogueText; node.audioToPlay = string.IsNullOrEmpty(jsonNode.audioToPlayPath) ? null : Resources.Load<AudioClip>(jsonNode.audioToPlayPath); node.animationToPlay = string.IsNullOrEmpty(jsonNode.animationToPlayPath) ? null : Resources.Load<AnimationClip>(jsonNode.animationToPlayPath); node.characterPanelColor = jsonNode.characterPanelColor; node.dialoguePanelColor = jsonNode.dialoguePanelColor; node.textColor = jsonNode.textColor; // Player fields node.playerName = jsonNode.playerName; node.playerSprite = string.IsNullOrEmpty(jsonNode.playerSpritePath) ? null : Resources.Load<Sprite>(jsonNode.playerSpritePath); node.playerEmotionalState = jsonNode.playerEmotionalState; node.isPlayerSpeaking = jsonNode.isPlayerSpeaking; nodeMap[jsonNode.id] = node; } foreach (DialogueManager.DialogueNode jsonNode in data.nodes) { DialogueNodeAuthoring node = nodeMap[jsonNode.id]; foreach (var jsonChoice in jsonNode.choices) { DialogueNodeAuthoring.Choice choice = new DialogueNodeAuthoring.Choice { choiceText = jsonChoice.choiceText, nextNode = string.IsNullOrEmpty(jsonChoice.nextNodeId) ? null : nodeMap[jsonChoice.nextNodeId], memoryKey = jsonChoice.memoryKey, // Add this memoryValue = jsonChoice.memoryValue // Add this }; node.Choices.Add(choice); } if (!string.IsNullOrEmpty(jsonNode.linearNextNodeId) && nodeMap.ContainsKey(jsonNode.linearNextNodeId)) { node.linearNextNode = nodeMap[jsonNode.linearNextNodeId]; } } Conversation newConvo = new Conversation { conversationName = fileName, dialogueRoot = dialogueRoot, startingNode = nodeMap.ContainsKey("Start") ? nodeMap["Start"].gameObject : dialogueRoot.transform.GetChild(0).gameObject, jsonFile = GetRelativePath(path) }; conversations.Add(newConvo); if (defaultDialogueRoot == null && defaultStartingNode == null) { defaultDialogueRoot = dialogueRoot; defaultStartingNode = newConvo.startingNode; if (DialogueManager.debugEnabled) Debug.Log(quot;Set defaultDialogueRoot and defaultStartingNode to imported conversation '{fileName}'."); } EditorUtility.SetDirty(this); if (DialogueManager.debugEnabled) Debug.Log(quot;Imported conversation '{fileName}' from {path} into GameObject hierarchy under {npcName}."); if (npcMemoryComponent == null) { npcMemoryComponent = memoryComponent; // Use imported memory if not already set } } private string GetResourcePath(Object asset) { if (asset == null) return ""; string path = AssetDatabase.GetAssetPath(asset); if (string.IsNullOrEmpty(path)) return ""; if (path.StartsWith("Assets/Resources/")) { return path.Substring("Assets/Resources/".Length) .Replace(".asset", "") .Replace(".sprite", "") .Replace(".wav", "") .Replace(".anim", ""); } if (DialogueManager.debugEnabled) Debug.LogWarning(quot;Asset {asset.name} is not in Resources folder: {path}. Move it to Resources for JSON loading!"); return ""; } private string GetRelativePath(string absolutePath) { string resourcesRoot = "Assets/Resources/"; int index = absolutePath.IndexOf(resourcesRoot); if (index >= 0) { string relativePath = absolutePath.Substring(index + resourcesRoot.Length).Replace(".json", ""); return relativePath; } if (DialogueManager.debugEnabled) Debug.LogWarning(quot;Imported JSON path {absolutePath} is outside Assets/Resources—setting as absolute, but it should be in Resources!"); return absolutePath; } private string EnsureAssetInResources(Object asset, string subFolder) { if (asset == null) return ""; string originalPath = AssetDatabase.GetAssetPath(asset); if (string.IsNullOrEmpty(originalPath)) return ""; if (originalPath.Contains("unity_builtin_extra")) { if (DialogueManager.debugEnabled) Debug.LogWarning(quot;Asset {asset.name} is a built-in Unity resource (unity_builtin_extra)—cannot copy to Resources, setting path to empty."); return ""; } if (originalPath.StartsWith("Assets/Resources/")) { return originalPath.Substring("Assets/Resources/".Length) .Replace(".asset", "") .Replace(".sprite", "") .Replace(".wav", "") .Replace(".anim", ""); } string fileName = Path.GetFileName(originalPath); string targetFolder = quot;Assets/Resources/{subFolder}"; if (!Directory.Exists(targetFolder)) { Directory.CreateDirectory(targetFolder); AssetDatabase.Refresh(); } string targetPath = quot;{targetFolder}/{fileName}"; if (!File.Exists(targetPath)) { AssetDatabase.CopyAsset(originalPath, targetPath); AssetDatabase.Refresh(); if (DialogueManager.debugEnabled) Debug.Log(quot;Copied asset {fileName} from {originalPath} to {targetPath} for JSON export."); } return quot;{subFolder}/{Path.GetFileNameWithoutExtension(fileName)}"; } void OnValidate() { if (conversations != null) { conversationToExportIndex = Mathf.Clamp(conversationToExportIndex, 0, Mathf.Max(0, conversations.Count - 1)); } } #endif } [System.Serializable] public class TimeSinceStartCondition { public float requiredTime; public bool IsMet(NPCConversationManager manager) { return Time.time >= requiredTime; } } [System.Serializable] public class MemoryCondition { public string memoryKey; public bool requiredValue; public bool IsMet(NPCConversationManager manager) { return manager.GetMemory(memoryKey) == requiredValue; } } [System.Serializable] public class RandomChanceCondition { [Range(0f, 1f)] public float chance; public bool IsMet(NPCConversationManager manager) { return UnityEngine.Random.value <= chance; } } ```