# Dialogue System in Unity: Scripts Breakdown This document explains a Unity dialogue system composed of several scripts: `DialogueManager.cs`, `DialogueNodeAuthoring.cs`, `Environment.cs`, `NPCConversationManager.cs`, `NPCMemory.cs`, and `TypewriterEffect.cs`. It details each script’s purpose, functionality, key methods, how they work together, and the GameObjects required to implement the system. --- ## Overview of the Dialogue System This system enables interactive NPC conversations in a 2D Unity game, supporting: - **Dialogue nodes** with branching choices - **NPC memory** to track past interactions - **Environmental effects** (background images, ambient audio) - **Player and NPC dialogue** with UI panels - **Typewriter-style text display** - **JSON export/import** for dialogue data The scripts collaborate to manage dialogue flow, NPC interactions, and UI updates. --- ## 1. [[DialogueManager.cs]] ### Purpose The core manager for handling dialogue flow, UI updates, audio, animations, and environment settings. It’s a **singleton** ensuring only one instance exists. ### How It Works - Manages a dictionary of `DialogueNode` objects (individual dialogue lines/choices) - Updates UI (character name, sprite, dialogue text, etc.) based on the current node - Handles **typing effects**, audio playback, animations, and choice selection - Supports **linear dialogue** (no choices) and **branching dialogue** (with choices) ### Key Methods - `Awake()`: Sets up the singleton and ensures no duplicates. Initializes audio sources. - `Start()`: Validates UI/component assignments, logs errors if missing. - `Update()`: Listens for input to advance dialogue (`advanceKey`, default `C`) or skip typing (`Space`). - `LoadDialogueFromGameObjects(GameObject dialogueRoot)`: Loads dialogue nodes from a GameObject hierarchy into `nodeLookup`. - `LoadDialogueFromFile(string fileName)`: Loads dialogue from a JSON file into `nodeLookup`. - `StartDialogue(DialogueNodeAuthoring startingNode)` / `StartDialogue(string startingNodeId)`: Begins dialogue from a specified node. - `UpdateDialogue()`: Updates UI, audio, and animations based on the current node. Manages panel visibility, colors, and choice buttons. - `TypeText(string text)`: Coroutine for typewriter effect, displaying text character by character. - `SkipTyping()`: Instantly displays full text if the player presses `Space`. - `AdvanceToNextNode()`: Moves to the next node if no choices exist. - `OnChoiceSelected(int choiceIndex)`: Handles choice selection, updates NPC memory, and moves to the next node. - `EndDialogue()`: Resets UI and stops audio/animations when dialogue ends. - `IsDialogueActive()`: Checks if the dialogue panel is active. - `AutoCloseDialogue()`: Coroutine to auto-close dialogue after a delay if no choices/next nodes exist. ### GameObjects Needed - **DialogueManager GameObject**: Must have this script and an `AudioSource`. - **UI Elements**: - `dialoguePanel`: GameObject with an `Image` for the dialogue background - `characterPanel`: GameObject with an `Image` for the NPC’s panel - `playerPanel`: GameObject for the player’s panel - `dialogueText`, `characterNameText`, `emotionalStateText`, `playerNameText`, `playerEmotionalStateText`: `TMP_Text` components - `characterSpriteImage`, `playerSpriteImage`, `environmentImage`: `Image` components - `choiceButtons`: Array of `Button` components for choices - **Audio Sources**: - `npcDialogueAudioSource`: For dialogue audio clips - `ambientAudioSource`: For background audio (assigned in `Awake`) - `typingAudioSource`: For typing sounds (child GameObject named "TypingAudioSource") - **Animation**: - `characterAnimation`: An `Animation` component for character animations --- ## 2. [[DialogueNodeAuthoring.cs]] ### Purpose Defines a dialogue node in the Unity Editor, allowing designers to set up dialogue data (text, choices, sprites, etc.) on GameObjects. ### How It Works - Each `DialogueNodeAuthoring` component represents a single dialogue node - Stores data like character name, sprite, dialogue text, choices, and visual settings - Choices can link to other nodes and set NPC memory values ### Key Fields - `Id`: Uses the GameObject’s name as the node’s unique identifier - `characterName`, `characterSprite`, `emotionalState`, `dialogueText`: NPC dialogue data - `Choices`: List of `Choice` objects (text, next node, memory settings) - `linearNextNode`: Next node if no choices - `playerName`, `playerSprite`, `playerEmotionalState`, `isPlayerSpeaking`: Player dialogue data ### GameObjects Needed - **Dialogue Node GameObjects**: Each node is a GameObject with this script. Typically children of a "dialogue root". - **Dialogue Root GameObject**: Parent GameObject holding all dialogue nodes and an `Environment` component --- ## 3. [[Environment.cs]] ### Purpose Defines environmental settings for a dialogue scene (background images, ambient audio). ### How It Works - Attached to the dialogue root GameObject - Provides a sprite (`environmentImage`) and audio clip (`ambientAudio`) for the scene ### Key Fields - `environmentImage`: Background sprite - `ambientAudio`: Ambient audio clip ### GameObjects Needed - **Dialogue Root GameObject**: Must have this script to define the environment --- ## 4. [[NPCConversationManager.cs]] ### Purpose Manages NPC interactions, conversation selection, and JSON export/import for dialogue data. Handles player proximity and triggers conversations. ### How It Works - Uses a 2D trigger collider to detect player proximity - Displays a prompt UI when the player is near - Selects a conversation based on conditions (time, memory, random chance) - Initiates dialogue via `DialogueManager` - Supports JSON export/import for dialogue data ### Key Methods - `Start()`: Initializes references, ensures collider is a trigger - `Update()`: Listens for `testKey` (default `T`) to start a conversation, manages prompt UI timer - `OnTriggerEnter2D(Collider2D other)`: Shows prompt when player enters NPC range - `OnTriggerExit2D(Collider2D other)`: Hides prompt, ends conversation if player leaves - `ShowPrompt()` / `HidePrompt()`: Toggles interaction prompt UI - `InitiateConversation()`: Starts a conversation by selecting one or using the default - `SelectConversation()`: Evaluates conditions (`TimeSinceStartCondition`, `MemoryCondition`, `RandomChanceCondition`) to choose a conversation - `SetMemory(string key, bool value)` / `GetMemory(string key, bool defaultValue)`: Manages NPC memory via `NPCMemory` - `ExportSelectedConversationToJson()`, `ExportAllConversationsToJson()`, `ImportConversationFromJson()`: Editor methods for JSON serialization/deserialization - `EnsureAssetInResources(Object asset, string subFolder)`: Ensures assets are in the Resources folder for JSON loading ### GameObjects Needed - **NPC GameObject**: Needs `NPCConversationManager`, `NPCMemory`, `AudioSource`, `CircleCollider2D` (trigger) - **Player GameObject**: Must have tag "Player" for trigger detection - **Interaction Prompt UI**: GameObject with `TMP_Text` for the prompt - **Dialogue Root GameObject**: Contains dialogue nodes and `Environment` - **Starting Node GameObject**: First dialogue node for each conversation --- ## 5. [[NPCMemory.cs]] ### Purpose Manages persistent memory for NPCs, tracking past player choices to influence future conversations. ### How It Works - Stores memory as key-value pairs in a `Dictionary` and `List` for serialization - Provides methods to set/get memory values ### Key Methods - `Awake()`: Initializes memory dictionary from the serialized list - `SetMemory(string key, bool value)`: Updates/adds a memory entry - `GetMemory(string key, bool defaultValue)`: Retrieves a memory value or returns a default - `GetMemoryList()` / `SetMemoryList(List<MemoryEntry> newList)`: Manages memory list for JSON serialization ### GameObjects Needed - **NPC GameObject**: Must have this script to store memory --- ## 6. [[TypewriterEffect.cs]] ### Purpose Provides a standalone typewriter effect for displaying dialogue text, separate from the main system. ### How It Works - Displays dialogue lines character by character with a typing sound - Supports skipping the effect and advancing with a continue button ### Key Methods - `Start()`: Initializes the continue button, starts the first dialogue line - `Update()`: Listens for `Return` to start typing (optional), `Space` to skip - `StartTyping(string text)`: Begins typewriter effect for a text - `TypeText()`: Coroutine adding characters one by one - `StopTyping()`: Instantly displays full text - `ShowContinueButton()`: Shows continue button when typing is done - `OnContinueClicked()`: Advances to the next line or ends dialogue ### GameObjects Needed - **Typewriter GameObject**: Must have this script - **Dialogue Text**: `TMP_Text` component for dialogue - **Continue Button**: `Button` component to advance - **Typing Sound**: `AudioSource` for typing sound --- ## How They Work Together 1. **NPC Interaction**: - Player enters NPC’s `CircleCollider2D` (`NPCConversationManager`) - Prompt appears (`ShowPrompt`) - Pressing `T` calls `InitiateConversation()`, selecting a conversation (`SelectConversation`) 2. **Dialogue Loading**: - `NPCConversationManager` passes conversation data to `DialogueManager` - `DialogueManager` loads dialogue from GameObjects (`LoadDialogueFromGameObjects`) or JSON (`LoadDialogueFromFile`) 3. **Dialogue Flow**: - `DialogueManager` starts dialogue (`StartDialogue`), updates UI (`UpdateDialogue`) - `Environment` provides background/audio - `DialogueNodeAuthoring` defines text, choices, visuals - Player advances with `C`, skips typing with `Space`, or selects choices via buttons 4. **Memory**: - Choices set memory (`NPCMemory`) via `SetMemory`, influencing future conversations (`MemoryCondition`) 5. **Typewriter Effect**: - `DialogueManager` uses its typewriter effect (`TypeText`), but `TypewriterEffect` can be used independently 6. **JSON Export/Import**: - `NPCConversationManager` exports dialogue to JSON (`ExportSelectedConversationToJson`) and imports it (`ImportConversationFromJson`), preserving memory (`NPCMemory`) --- ## GameObjects Needed for the Full System 1. **NPC**: - `NPCConversationManager`, `NPCMemory`, `AudioSource`, `CircleCollider2D` (trigger) - **Child**: Interaction prompt UI (`TMP_Text`) 2. **Dialogue Manager**: - `DialogueManager`, `AudioSource` - **Child**: `TypingAudioSource` GameObject with `AudioSource` - **UI**: `dialoguePanel`, `characterPanel`, `playerPanel`, `dialogueText`, `characterNameText`, `emotionalStateText`, `playerNameText`, `playerEmotionalStateText`, `characterSpriteImage`, `playerSpriteImage`, `environmentImage`, `choiceButtons` - `characterAnimation` (optional) 3. **Dialogue Root**: - `Environment` - **Children**: Dialogue nodes with `DialogueNodeAuthoring` 4. **Player**: - Tag: "Player" 5. **Typewriter (Optional)**: - `TypewriterEffect` - **UI**: `dialogueText`, `continueButton` - `typingSound` (`AudioSource`) --- ## Summary - **DialogueManager**: Orchestrates dialogue flow, UI, effects - **DialogueNodeAuthoring**: Defines dialogue content in Editor - **Environment**: Sets scene background/audio - **NPCConversationManager**: Handles NPC interactions, conversation selection - **NPCMemory**: Tracks choices for dynamic conversations - **TypewriterEffect**: Standalone typewriter effect Together, they create a robust dialogue system for a 2D RPG or narrative game, supporting branching conversations, memory, and environmental immersion.