Scripting

The Dialogue System has a comprehensive API for programmers. For visual scripting, the Dialogue System supports several visual scripting systems including Playmaker Support, Makinom Support, and Unity's Visual Scripting Support package.

This is the Dialogue System for Unity's Scripting Reference. The API reference is integrated with this manual. Click the buttons above to view Namespaces, Classes, and Files, or use the search bar in the upper right.

A common use of scripting is to integrate with other code, either your project's custom code or other Asset Store assets. For general integration tips, see General Integration Tips. The Dialogue System includes integration packages for many assets. For the list of assets and their integration instructions, see Third Party Integration.

Assembly Definition Files

The use of assembly definitions (asmdefs) is optional. Since the Dialogue System imports into Plugins, it compiles separately from your project's code, so it won't impact compile times of your code.

If you do want to use asmdefs, import Plugins/Pixel Crushers/Dialogue System/Scripts/DialogueSystemAssemblyDefinitions.unitypackage. This will import four asmdef files: PixelCrushers, PixelCrushersEditor, DialogueSystem, and DialogueSystemEditor.

If you import the Dialogue System asmdefs and enable integrations with packages that use asmdefs, you must also add references to those asmdefs to the Dialogue System asmdefs. Since we can't know ahead of time what integrations you will enable, it's not possible to add those asmdef references ahead of time. However, we've added references to some of the most commonly-used Unity packages: Addressables, Cinemachine, Input System, TextMesh Pro, and Timeline. If those packages are not installed in your project, the references will be ignored.

Addressables note: DialogueSystem.asmdef has a reference to Unity.Addressables.Editor. This reference will only be used in the Unity editor. It won't be compiled into builds. The Dialogue System's PreviewUI script needs to use some editor-specific code when previewing addressable audio clips in the Timeline editor. This gets compiled out in builds, though.

Source Code Overview

Namespaces

All Dialogue System source code is contained within the namespace hierarchy PixelCrushers.DialogueSystem.

Pixel Crushers Common Library source code is in the PixelCrushers namespace.

LuaInterpreter is contained in the namespace Language.Lua.

Code Overview

The Dialogue System uses a Model-View-Controller (MVC) architecture:

MVC Description
Model State of the dialogue database, Lua, and active conversation.
View Dialogue UI and cutscene sequencer.
Controller Mediates between the model and the view.

However, the entire MVC architecture is managed by the PixelCrushers.DialogueSystem.DialogueManager. To control the Dialogue System you'll generally only need to use DialogueManager methods.

For more information about the relationship between dialogue database fields and Lua values, see Dialogue Database Fields and Lua Values.

Templates

The Templates ► Scripts folder contains templates that you can copy to create your own implementations of dialogue UIs, bark UIs, sequencer commands, and persistent data recorders.

Scripting Define Symbols

The Dialogue System supports a number of scripting define symbols such as TMP_PRESENT to enable support for TextMesh Pro and USE_TIMELINE to enable support for Timeline. You can view and enable or disable these symbols in the Dialogue System's Welcome Window. The exception is LATEUPDATE_MESSAGES:

Sequencer Messages in Late Update

The ->Message syntax in Cutscene Sequences allows you to send a sequencer message when a sequencer command has completed. It normally sends the message as soon as the command completes. If you want to delay the message until LateUpdate (e.g., after animation updates), manually add the scripting define symbol LATEUPDATE_MESSAGES. To add it, select menu item Edit > Project Settings > Player > Other Settings. Add it to Scripting Define Symbols.

Commonly Used Methods

Below are some of the most commonly used script methods. Each class below has many other useful methods, too. These are just the methods that you're most likely to use if you're writing scripts to work with the Dialogue System.

DialogueManager Class

PixelCrushers.DialogueSystem.DialogueManager.Bark:

DialogueManager.Bark("Converation With Bark Lines", barker.transform);

PixelCrushers.DialogueSystem.DialogueManager.BarkString:

DialogueManager.BarkString("I'm barking this text.", barker.transform);

PixelCrushers.DialogueSystem.DialogueManager.GetLocalizedText:

DialogueManager.SetLanguage("fr");
string frenchForCheese = DialogueManager.GetLocalizedText("cheese");

PixelCrushers.DialogueSystem.DialogueManager.PlaySequence:

DialogueManager.PlaySequence("Fade(in,2); Audio(Tada)@2");

PixelCrushers.DialogueSystem.DialogueManager.SendUpdateTracker:

DialogueManager.SendUpdateTracker(); // Manually refresh quest tracker HUD & quest log window displays.

PixelCrushers.DialogueSystem.DialogueManager.ShowAlert:

DialogueManager.ShowAlert("This is an alert.");

PixelCrushers.DialogueSystem.DialogueManager.StartConversation:

DialogueManager.StartConversation("Some Conversation", actor.transform, conversant.transform);

PixelCrushers.DialogueSystem.DialogueManager.StopConversation:

DialogueManager.StopConversation();

PixelCrushers.DialogueSystem.DialogueManager.instance Points to the current instance of the PixelCrushers.DialogueSystem.DialogueSystemController: component, which is the MonoBehaviour for which DialogueManager is a wrapper.

PixelCrushers.DialogueSystem.DialogueSystemController.isInitialized PixelCrushers.DialogueSystem.DialogueSystemController.initializationComplete: DialogueSystemController initializes itself in Start(). When complete, it invokes the initializationComplete event, which your code can hook into. The isInitialized property indicates that initialization is complete. You can use initializationComplete or isInitialized to know when the DialogueSystemController is fully initialized in your own Start() methods since it's possible that your own Start() method could start before the DialogueSystemController's Start() method.

DialogueLua Class

PixelCrushers.DialogueSystem.DialogueLua.GetVariable:

string s = DialogueLua.GetVariable("favoriteColor").asString;

PixelCrushers.DialogueSystem.DialogueLua.SetVariable:

DialogueLua.SetVariable("favoriteColor", "blue");

QuestLog Class

PixelCrushers.DialogueSystem.QuestLog.GetQuestState:

QuestState state = QuestLog.GetQuestState("The Holy Grail");

PixelCrushers.DialogueSystem.QuestLog.SetQuestState:

QuestLog.SetQuestState("The Holy Grail", QuestState.Active);

PixelCrushers.DialogueSystem.QuestLog.GetAllQuests:

string[] quests = QuestLog.GetAllQuests()

SaveSystem Class

PixelCrushers.SaveSystem.SaveToSlot:

SaveSystem.SaveToSlot(1);

PixelCrushers.SaveSystem.LoadFromSlot:

SaveSystem.LoadFromSlot(1);

PixelCrushers.SaveSystem.LoadScene:

SaveSystem.LoadScene("Tavern@Entryway"); // Load Tavern scene, move player to position of Entryway GameObject.

Other Classes & Methods

The Dialogue System has an extensive API that allows you to control every aspect. The API reference is integrated with this manual. To search for something, enter it in the search bar at the upper right of this page, or click the Classes tab at the top of the page.

Dialogue System Attributes

You can use the attributes below in your own scripts.

ConversationPopup Attribute

Use the [ConversationPopup] attribute to turn a string into a conversation popup. It has two optional bool parameters:

  1. Show a database selection field
  2. Show a filter field to narrow the popup list
using UnityEngine;
public class MyClass : MonoBehaviour {
[ConversationPopup]
public string conversation; // Shown without database selection field.
[ConversationPopup(true)]
public string conversation2; // Shown WITH database selection field.
[ConversationPopup(false, true)]
public string conversation3; // Shown without database selection field but with filter field.
}
Definition DemoInputRegistration.cs:4

DialogueEntryPopup Attribute

Use the [DialogueEntryPopup] attribute in your class definition to turn an int into a dialogue entry ID popup. NOTE: This attribute will only work if your script also has a string variable named 'conversation', 'conversationTitle', 'conversationName', 'Conversation', 'ConversationTitle', or 'ConversationName'. This is how the dialogue entry popup knows which conversation's entries to show. This attribute also does not support lists of serialized classes.

using UnityEngine;
public class MyClass : MonoBehaviour {
[ConversationPopup]
public string conversation;
[DialogueEntryPopup]
public int dialogueEntry; // Shows a popup with the dialogue entries in conversation.
}

QuestPopup Attribute

Use the [QuestPopup] attribute in your class definition to turn a string into a quest popup. It has an optional bool parameter to show a database selection field.

using UnityEngine;
public class MyClass : MonoBehaviour {
[QuestPopup]
public string questName; // Shown without database selection field.
[QuestPopup(true)]
public string questName2; // Shown WITH a database selection field.
}

QuestEntryPopup Attribute

Use the [QuestEntryPopup] attribute in your class definition to turn an int into a quest entry popup. NOTE: This attribute will only work if your script also has a string variable named 'quest', 'questTitle', 'questName', 'Quest', 'QuestTitle', or 'QuestName'. This is how the quest entry popup knows which quest's entries to show. This attribute also does not support lists of serialized classes.

using UnityEngine;
public class MyClass : MonoBehaviour {
[QuestPopup]
public string questName;
[QuestEntryPopup]
public int questEntry; // Shows a popup with the entries defined in the quest named by the previous quest popup (questName).
}

QuestState Attribute

The [QuestState] attribute changes the quest state popup to use lowercase letters so it matches the case used in Lua.

using UnityEngine;
public class MyClass : MonoBehaviour {
public QuestState myQuestState;
}
QuestState
Quest state is a bit-flag enum that indicates the state of a quest.
Definition QuestState.cs:12

ItemPopup Attribute

Use the [ItemPopup] attribute in your class definition to turn a string into an item popup. It has an optional bool parameter to show a database selection field.

using UnityEngine;
public class MyClass : MonoBehaviour {
[ItemPopup]
public string item; // Example: Shown without database selection field.
}

ActorPopup Attribute

Use the [ActorPopup] attribute in your class definition to turn a string into an actor popup. It has an optional bool parameter to show a database selection field.

using UnityEngine;
public class MyClass : MonoBehaviour {
[ActorPopup]
public string actor; // Example: Shown without database selection field.
}

VariablePopup Attribute

Use the [VariablePopup] attribute in your class definition to turn a string into a variable popup. It has an optional bool parameter to show a database selection field.

using UnityEngine;
public class MyClass : MonoBehaviour {
[VariablePopup]
public string variable; // Example: Shown without database selection field.
}

Lua Wizard Attributes

Use the [LuaConditionWizard] and [LuaScriptWizard] attributes in your class definition to turn a string into a Lua wizard field. This allows you to assign Lua code to the string using the Point-and-Click Lua wizards.

using UnityEngine;
public class MyClass : MonoBehaviour {
public string myLuaCondition;
public string myLuaScript;
}
This Lua condition wizard is meant to be called from a custom editor's OnInspectorGUI() method.
Definition LuaConditionWizard.cs:18
This Lua script wizard is meant to be called from a custom editor's OnInspectorGUI() method.
Definition LuaScriptWizard.cs:17

Script Messages & Events

The Dialogue System sends several useful messages that your scripts can handle. It also has corresponding C# events that you can hook into.

You may also find it convenient to hook up events visually in the inspector using the Dialogue System Events component.

C# Events

Event Description
DialogueManager.instance.initializationComplete Dialogue System has completely initialized, including loading the initial dialogue database and registering Lua functions.
DialogueManager.instance.conversationStarted Conversation has started. Parameter is primary actor's transform.
DialogueManager.instance.conversationEnded Conversation has ended. Parameter is primary actor's transform.
DialogueManager.instance.overrideGetLocalizedText Assign to override the default GetLocalizedText() method.
Sequencer.receivedMessage Called by a Sequencer object when it receives a sequencer message.

Conversation, Bark, and Sequence Messages

The Dialogue System sends these messages to the participants involved:

Conversation Messages

Message Recipient Description
OnConversationStart(Transform actor) Participants, Dialogue Manager & children Sent at the start of a conversation. The actor is the other participant in the conversation.
OnConversationEnd(Transform actor) Participants, Dialogue Manager & children Sent at the end of a conversation, after the dialogue UI has closed. The actor is the other participant in the conversation.
OnConversationCancelled(Transform actor) Participants, Dialogue Manager & children Sent if a conversation ended because the player pressed the cancel key or button during the player response menu.
OnPrepareConversationLine(DialogueEntry) Dialogue Manager only Sent prior to evaluating a dialogue entry's links and preparing it to be spoken. Note: Also sent prior to preparing a bark.
OnConversationLine(Subtitle subtitle) Participants, Dialogue Manager & children Sent just before a line is spoken. See the PixelCrushers.DialogueSystem.Subtitle reference. Your method can modify the subtitle before it's displayed.
OnConversationLineEnd(Subtitle subtitle) Participants, Dialogue Manager & children Sent at the end of a line, including if the line is cancelled.
OnConversationLineCancelled(Subtitle subtitle) Participants, Dialogue Manager & children Sent if the player pressed the cancel key or button while a line was being delivered. Cancelling causes the Dialogue System to jump to the end of the line and continue to the next line or response menu.
OnConversationTimeout() Dialogue Manager only Sent if the response menu timed out. The DialogueSystemController script handles timeouts according to its display settings. You can add your own scripts to the Dialogue Manager object that also listens for this message. See Example: Custom Timeout Handler for an example.
OnConversationResponseMenu(Response[] responses) Dialogue Manager & children Sent before showing a response menu. See the PixelCrushers.DialogueSystem.Response reference. Your method can modify the content of the responses.
OnLinkedConversationStart(Transform actor) Participants, Dialogue Manager & children Sent when an active conversation follows a cross-conversation link to a different conversation in the dialogue database.
OnTextChange(UnityEngine.UI.Text) Only Unity/Standard UI Dialogue UI Sent when a Unity UI Dialogue UI Text element changes

Bark Messages

Message Recipient Description
OnBarkStart(Transform actor) Participants, Dialogue Manager & children Sent at the start of a bark. The actor is the other participant.
OnBarkEnd(Transform actor) Participants, Dialogue Manager & children Sent at the end of a bark. The actor is the other participant.
OnBarkLine(Subtitle subtitle) Speaker, Dialogue Manager & children Send at the start of a bark before the line is barked. Your method can modify the subtitle before it's barked.

Sequence Messages

Message Recipient Description
OnSequenceStart(Transform actor) Speaker & listener Sent at the beginning of a cutscene sequence. The actor is the other participant. (Sequences can have an optional speaker and listener.)
OnSequenceEnd(Transform actor) Speaker & listener Sent at the end of a sequence. The actor is the other participant.
OnSequencerMessage(string msg) Dialogue Manager Sent when sending a sequencer message.

Example: Conversation Logger

The sample script below logs conversation activity. Add it to an actor such as the player.

using UnityEngine;
using PixelCrushers.DialogueSystem;
 
public class LogConversation : MonoBehaviour {
 
public void OnConversationStart(Transform actor) {
Debug.Log(string.Format("Starting conversation with {0}", actor.name));
}
 
public void OnConversationLine(Subtitle subtitle) {
Debug.Log(string.Format("{0}: {1}", subtitle.speakerInfo.transform.name, subtitle.formattedText.text));
}
 
public void OnConversationEnd(Transform actor) {
Debug.Log(string.Format("Ending conversation with {0}", actor.name));
}
 
}
Transform transform
The transform of the character's GameObject.
Definition CharacterInfo.cs:52
string text
Gets or sets the "clean" line of text, without formatting codes.
Definition FormattedText.cs:45
Info about a line of dialogue.
Definition Subtitle.cs:14
FormattedText formattedText
The formatted text of the line.
Definition Subtitle.cs:29
CharacterInfo speakerInfo
Info about the speaker of this line.
Definition Subtitle.cs:19

Notes:

  • This is a simplified version of the Conversation Logger component.
  • The string DialogueManager.LastConversationStarted records the last conversation that was started, or the current conversation if a conversation is active.

Example: Custom Timeout Handler

The sample script below restarts the conversation at the beginning if the response menu times out. Add it to the Dialogue Manager. It works best when the Dialogue Manager's Input Settings > Response Timeout Action is set to Custom.

using UnityEngine;
using PixelCrushers.DialogueSystem;
public class GotoBeginningOnTimeout : MonoBehaviour
{
void OnConversationTimeout()
{
}
}
void GotoState(ConversationState state)
Goes to a conversation state.
Definition ConversationController.cs:222
ConversationState firstState
The first state in the conversation, which is the root of the dialogue tree.
Definition ConversationModel.cs:37
A static class that provides a simplified interface to the Dialogue System's core functions.
Definition DialogueManager.cs:14
static ConversationModel conversationModel
Gets the active conversation's ConversationModel.
Definition DialogueManager.cs:201
static ConversationController conversationController
Gets the active conversation's ConversationController.
Definition DialogueManager.cs:196

Quest Messages

Quest log windows broadcast the following messages to the Dialogue Manager when the player toggles quest tracking. You can add a script to the Dialogue Manager or a child object that handles the message – for example, turning on a gameplay HUD.

Message Recipient Description
OnQuestStateChange(string title) Dialogue Manager & children Sent when a quest state or quest entry state changes via the QuestLog class and/or Lua functions SetQuestState and SetQuestEntryState.
OnQuestEntryStateChange(QuestEntryArgs args) Dialogue Manager & children Sent when a quest entry state changes. QuestEntryArgs is a struct with two fields: (string)questName and (int)entryNumber.
OnQuestTrackingEnabled(string questTitle) Dialogue Manager & children Sent when tracking is enabled.
OnQuestTrackingDisabled(string questTitle) Dialogue Manager & children Sent when tracking is disabled or a quest is abandoned.

You can also hook into several QuestLog delegates:

  • StringToState: You can reassign this delegate method to override the default conversion of strings to QuestStates.
  • CurrentQuestStateOverride: You can assign a method to override the default CurrentQuestState.
  • SetQuestStateOverride: You can assign a method to override the default SetQuestState.
  • CurrentQuestEntryStateOverride: You can assign a method to override the default CurrentQuestEntryState.
  • SetQuestEntryStateOverride: You can assign a method to override the default SetQuestEntryState.

Other Messages

Message Recipient Description
OnShowAlert(string message) Dialogue Manager & children Sent when DialogueManager.ShowAlert() is called.
OnDialogueSystemPause() Conversation participants, Dialogue Manager & children Sent when DialogueManager.Pause() is called.
OnDialogueSystemUnpause() Conversation participants, Dialogue Manager & children Sent when DialogueManager.Unpause() is called.
OnUse(Transform actor) Targeted Usable Sent by Selector and Proximity Selector.

IsDialogueEntryValid Delegate

Normally, you will add conditions on a dialogue entry using its Conditions field, specified in Lua code. However, if you need to perform extra checking outside of Lua, you can set the Dialogue Manager's IsDialogueEntryValid delegate. This is a C# method that returns true or false. If it returns true, the dialogue entry is considered for use in the current conversation.

Example:

DialogueManager.IsDialogueEntryValid = IsMyDialogueEntryValid;
public bool IsMyDialogueEntryValid(DialogueEntry dialogueEntry) {
// Return true if the entry is valid to use right now;
// otherwise return false.
}
A dialogue entry is a single line of dialogue in a Conversation, with a list of links to possible res...
Definition DialogueEntry.cs:20

IsDialogueEntryValid Example

Here's a real world example of IsDialogueEntryValid. It's in a subclass of StandardDialogueUI, but you could put it anywhere.

  • The Start() method registers the delegate IsSpeakerNearby().
  • Whenever the Dialogue System considers using a dialogue entry, it calls this delegate. If it returns true, the entry is kept in consideration. If it returns false, the entry is rejected.
  • In this example, IsSpeakerNearby() examines the entry's Actor ID. If the actor isn't close enough to the player, it returns false. The functions to check distance aren't shown in this example.
public class MyDialogueUI : StandardDialogueUI {
// In Start, set up the extra line-checking delegate (to make sure actors are nearby):
public override void Start () {
base.Start();
DialogueManager.IsDialogueEntryValid = IsSpeakerNearby;
}
// This is an additional check on dialogue entries. If the actor isn't nearby, the entry is rejected:
public bool IsSpeakerNearby(DialogueEntry entry) {
if (entry == null) return false;
// Always return true for the conversation's primary Actor and Conversant:
if (IsAPrimaryConversationActor(entry)) return true;
// Now that we have the isActorNearby[] value, check it:
if (IsActorNearby(entry.ActorID)) {
return true;
} else {
if (DialogueDebug.LogInfo) Debug.Log(string.Format("{0}: IsSpeakerNearby: actor {1} (ID {2}) is NOT nearby", DialogueDebug.Prefix, GetActorTag(entry.ActorID), entry.ActorID));
return false;
}
}
}
virtual void Start()
Starts this instance by hiding everything.
Definition AbstractDialogueUI.cs:81
A simple static class to keep track of a global debug level setting for Dialogue System log messages.
Definition DialogueDebug.cs:16
const string Prefix
Dialogue system log messages are prefixed with this string.
Definition DialogueDebug.cs:21
int ActorID
Gets or sets the ID of the line's actor (speaker).
Definition DialogueEntry.cs:113
Definition StandardDialogueUI.cs:12

UpdateResponses()

If you need to update the available choices in the player response menu while the response menu is already being displayed, call:

static void UpdateResponses()
Updates the responses for the current state of the current conversation.
Definition DialogueManager.cs:603

This updates the responses for the current state of the current conversation. For example, say your player is a shapeshifter in a fantasy game. When she talks to an NPC while in cat form, the response menu may contain choices specific to her cat form. But if she transforms into a dog while the response menu is displayed, call DialogueManager.UpdateResponses() to remove the cat-specific choices and add the dog-specific choices.

Dialogue Database Fields and Lua Values

A DialogueDatabase consists of Actor, Item, Location, Variable, and Conversation, objects that are all subclasses of the Asset class. Conversations contain DialogueEntry objects that are not a subclass of Asset but are nevertheless structured similarly.

These objects have a fields list, which is a list of Field objects. You can use static methods in the Field class such as Field.LookupValue to look up values from a fields list.

The Asset class – which Actors, Items, Locations, Variables, and Conversations inherit – also have helper methods such as Asset.LookupValue to simplify your code so you don't have to access the fields list directly.

At runtime, the Dialogue System loads values from your dialogue database asset into an in-memory version referenced by DialogueManager.masterDatabase. Then it loads the values from the dialogue database into a Lua virtual machine where the current values can be checked and changed during play. The important distinction is that dialogue database values (e.g., fields) should be treated as read-only during play. To check or change their current runtime values, use Lua.

The simplest way to check and change Lua values is to use the DialogueLua class. To work with quests, use the QuestLog class, which is a helper class built on top of DialogueLua that provides simpler functions for working with quests.

How to Create a Database in Script

This section contains information on manually creating and adding additional dialogue databases at runtime in a script.

Note that in addition to manually creating database contents, you can also import articy:draft XML and Chat Mapper XML at runtime. (See Import & Export.)

When creating a database, use the Template class. If the script runs in the editor, you can use TemplateTools.LoadFromEditorPrefs() to get a Template class that uses any template fields you've set up in the Dialogue Editor's Templates section. Otherwise use Template.FromDefault() like the example below. This example creates a new database and adds a conversation with a START node and one actual node:

// Create database:
var database = ScriptableObject.CreateInstance<DialogueDatabase>();
// Create a template, which provides helper methods for creating database content:
var template = Template.FromDefault();
// Create actors:
int playerID = template.GetNextActorID(database);
database.actors.Add(template.CreateActor(playerID, "Player", true));
int npcID = template.GetNextActorID(database);
database.actors.Add(template.CreateActor(npcID, "NPC", false));
// Create a conversation: [ID 0=START] --> [ID 1=Hello]
int conversationID = template.GetNextConversationID(database);
var conversationTitle = "My Conversation";
var conversation = template.CreateConversation(conversationID, conversationTitle);
conversation.ActorID = playerID;
conversation.ConversantID = npcID;
database.conversations.Add(conversation);
// START node: (Every conversation starts with a START node with ID 0)
var startNode = template.CreateDialogueEntry(0, conversation.id, "START");
node.ActorID = playerID;
node.ConversantID = npcID;
startNode.Sequence = "None()"; // START node usually shouldn't play a sequence.
conversation.dialogueEntries.Add(startNode);
// Actual dialogue node ("Hello") with ID 1: (could have used template.GetNextDialogueEntryID)
var helloNode = template.CreateDialogueEntry(1, conversation.id, string.Empty);
helloNode.ActorID = npcID; // NPC speaks this line.
helloNode.ConversantID = playerID;
helloNode.DialogueText = "Hello";
conversation.dialogueEntries.Add(helloNode);
// Link from START to Hello:
var link = new Link(conversation.id, startNode.id, conversation.id, node.id);
startNode.outgoingLinks.Add(link);
// And what the heck - might as well add it to the runtime environment and play it:
A dialogue database asset.
Definition DialogueDatabase.cs:16
void Add(DialogueDatabase database)
Add the contents of another database to this database.
Definition DialogueDatabase.cs:430
List< Conversation > conversations
The conversations in the database.
Definition DialogueDatabase.cs:78
static void AddDatabase(DialogueDatabase database)
Adds a dialogue database to memory.
Definition DialogueManager.cs:312
static void StartConversation(string title, Transform actor, Transform conversant, int initialDialogueEntryID, IDialogueUI overrideDialogueUI)
Starts a conversation, which also broadcasts an OnConversationStart message to the actor and conversa...
Definition DialogueManager.cs:476
This class defines the template that the Dialogue Database Editor will use when creating new dialogue...
Definition Template.cs:17
int GetNextActorID(DialogueDatabase database)
A value 1 higher than the highest actor ID in the database.
Definition Template.cs:211
static Template FromDefault()
Definition Template.cs:41

If you want to add extra fields to something in the database, use Field.SetValue() like this:

Field.SetValue(actor.fields, "Title", "Gunnery Sergeant");
Assets are composed primarily of data elements called fields.
Definition Field.cs:16
static void SetValue(List< Field > fields, string title, string value, FieldType type)
A static utility method that sets the string value of a field.
Definition Field.cs:341

Resolving ID Conflicts

Everything inside a database has an internal ID number: actors, items/quests, locations, variables, conversations, and dialogue entry nodes. They don't have to be sequential, but they do have to be unique among their type. That is, there should only be one actor with a specific ID, one conversation with a specific ID, etc. (But it's fine to have an actor with ID 42 and a conversation with ID 42 since they're different types.)

Internally, the Dialogue System looks up these resources by their IDs. If the initial database has a conversation with ID 42 and your newly-added database also has a conversation with ID 42, it won't know which one to use.

If you create multiple databases at design time, you can use the Unique ID Tool editor window to reassign IDs to resolve conflicts.

But if you're creating a database at runtime, you can't use this editor window. Instead, there are two ways to resolve the conflicts:

  1. When you create your database in code, use ID numbers that are guaranteed not to be in the initial database. For example, start all of your IDs at 10000. This solution is simple to implement.
  2. Or use the DatabaseMerger class. This is a static utility class that merges the contents of one database into another, resolving ID conflicts at the same time. Here's how you might use it:
// Make a copy of the initial database:
var mergedDatabase = Instantiate(DialogueManager.instance.initialDatabase);
// Merge in the newly-created database:
DatabaseMerge.Merge(mergedDatabase, newlyCreatedDatabase, ConflictingIDRule.AssignUniqueIDs, false, true, true, true, true, true);
// Remove the initial database from the Dialogue System's runtime environment:
// And add the merged database:
DialogueManager.AddDatabase(mergedDatabase);
static DialogueSystemController instance
Gets the instance of DialogueSystemController.
Definition DialogueManager.cs:25
static void RemoveDatabase(DialogueDatabase database)
Removes a dialogue database from memory.
Definition DialogueManager.cs:326
DialogueDatabase initialDatabase
The initial dialogue database.
Definition DialogueSystemController.cs:41

Customizing the Dialogue Editor

There are several ways to customize the Dialogue Editor window:

  • On the Database page, expand Editor Settings. You can specify how frequently to generate an auto-backup (zero to disable), whether to show the database name, etc.
  • The Conversations page's Menu also has several options to customize the way the node editor works.
  • To add your own menu items to the Conversation page's Menu, assign a handler to the static C# event DialogueEditorWindow.customNodeMenuSetup(DialogueDatabase, GenericMenu).
  • To draw additional information in the conversation inspector, assign a handler to DialogueEditorWindow.customDrawConversationInspector(DialogueDatabase, Conversation).
  • To add your own menu items to the Sequence field dropdown menu, assign a handler to SequenceEditorTools.customSequenceMenuSetup(GenericMenu). In the handler, you can call SequenceEditorTools.AddText(string) to add text to the sequence.
  • To add your own handling to the Sequence field's drag-n-drop functionality, assign a delegate method to SequenceEditorTools.tryDragAndDrop(UnityEngine.Object, ref string sequence).
  • To customize the way nodes are drawn, assign a handler to DialogueEditorWindow.customDrawDialogueEntryNode(DialogueDatabase, DialogueEntry, Rect).
  • To draw additional information in the dialogue entry inspector, assign a handler to DialogueEditorWindow.customDrawDialogueEntryInspector(DialogueDatabase, DialogueEntry).
  • To draw additional information in actor, item, and location inspectors, assign a handler to DialogueEditorWindow.customDrawAssetInspector(DialogueDatabase, Asset).
  • To perform additional searching in the Dialogue Editor's Database section > Global Search & Replace, assign a handler to customGlobalSearch and/or customGlobalSearchAndReplace.
  • Note: You can also add fields in the Dialogue Editor's Templates section and tick the Main checkbox to have them appear in the content's main inspector section.

Example template script:

using UnityEngine;
using UnityEditor;
using PixelCrushers.DialogueSystem;
using PixelCrushers.DialogueSystem.DialogueEditor;
[InitializeOnLoad]
public static class TestHooks
{
static TestHooks()
{
DialogueEditorWindow.customNodeContextMenuSetup += AddToDialogueEntryContextMenu;
DialogueEditorWindow.customGlobalSearch += AdditionalGlobalSearch;
DialogueEditorWindow.customGlobalSearchAndReplace += AdditionalGlobalSearchAndReplace;
SequenceEditorTools.customSequenceMenuSetup += AddItemsToSequenceMenu;
}
private static void AddToAssetInspector(DialogueDatabase database, Asset asset)
{
GUILayout.Label("Extra Info in " + asset.GetType().Name);
}
private static void AddToConversationInspector(DialogueDatabase database, Conversation conversation)
{
GUILayout.Label("Extra Info in conversation " + conversation.id);
}
private static void AddToEntryInspector(DialogueDatabase database, DialogueEntry entry)
{
GUILayout.Label("Extra Info in entry " + entry.id);
}
private static void AddToDialogueEntryContextMenu(DialogueDatabase database, DialogueEntry entry, GenericMenu contextMenu)
{
menu.AddDisabledItem(new GUIContent("Menu item when right-clicking on node"));
}
private static void AddItemsToNodeMenu(DialogueDatabase database, GenericMenu menu)
{
menu.AddDisabledItem(new GUIContent("Menu item in Menu dropdown"));
}
private static void AddToNodeDisplay(DialogueDatabase database, DialogueEntry entry, Rect boxRect)
{
GUI.Label(boxRect, "Test");
}
private static void AddItemsToSequenceMenu(GenericMenu menu)
{
menu.AddDisabledItem(new GUIContent("Test"));
// Use SequenceEditorTools.AddText("command") to add sequencer commands.
}
private static bool TryDragAndDrop(UnityEngine.Object obj, ref string sequence)
{
Debug.Log("Try drag: " + obj);
return false;
}
private static AdditionalGlobalSearch(DialogueDatabase database, string conversationTitle, string searchText, ref string result)
{
Debug.Log("Perform additional searches and append results to result variable.");
}
private static AdditionalGlobalSearchAndReplace(DialogueDatabase database, string conversationTitle, string searchText, string replaceText)
{
Debug.Log("Perform additional search & replace.");
}
}
The base class of all assets such as actors, conversations, items, locations and variables found in a...
Definition Asset.cs:15
string Name
Gets or sets the Name field.
Definition Asset.cs:36
int id
Every asset has an ID number.
Definition Asset.cs:21
A conversation asset.
Definition Conversation.cs:16
This part of the Dialogue Editor window handles conversation templates.
Definition DialogueEditorWindowConversationTemplates.cs:15
static DrawConversationInspectorDelegate customDrawConversationInspector
Assign handler(s) to perform extra drawing in the conversation inspector view.
Definition DialogueEditorWindowDelegates.cs:86
static GlobalSearchAndReplaceDelegate customGlobalSearchAndReplace
Assign handler(s) to perform extra global search & replace.
Definition DialogueEditorWindowDelegates.cs:115
static SetupDialogueEntryNodeContextMenuDelegate customNodeContextMenuSetup
Definition DialogueEditorWindowDelegates.cs:103
static DrawAssetInspectorDelegate customDrawAssetInspector
Assign handler(s) to perform extra drawing in Actor, Item, and Location inspector views.
Definition DialogueEditorWindowDelegates.cs:81
static DrawDialogueEntryInspectorDelegate customDrawDialogueEntryInspector
Assign handler(s) to perform extra drawing in the dialogue entry inspector view.
Definition DialogueEditorWindowDelegates.cs:91
static DrawDialogueEntryNodeDelegate customDrawDialogueEntryNode
Assign handler(s) to perform extra drawing on nodes in the node editor.
Definition DialogueEditorWindowDelegates.cs:96
static SetupGenericDialogueEditorMenuDelegate customNodeMenuSetup
Assign handler(s) to add extra menu items to the node editor menu.
Definition DialogueEditorWindowDelegates.cs:101
static GlobalSearchDelegate customGlobalSearch
Assign handler(s) to perform extra global search.
Definition DialogueEditorWindowDelegates.cs:109
int id
The dialogue entry ID.
Definition DialogueEntry.cs:25
This class provides a custom drawer for Sequence fields.
Definition SequenceEditorTools.cs:22
static TryDragAndDropDelegate tryDragAndDrop
Assign delegate handler to check extra drag-n-drop options.
Definition SequenceEditorTools.cs:27
static SetupGenericMenuDelegate customSequenceMenuSetup
Assign handler(s) to add extra menu items to the Sequence dropdown menu.
Definition SequenceEditorTools.cs:32

Batch Mode Compatibility

Unity supports running in batch mode in the Unity editor and Standalone builds: https://docs.unity3d.com/Manual/CLIBatchmodeCoroutines.html

The Dialogue System normally uses WaitForEndOfFrame operators, which are not supported in batch mode.

To use the Dialogue System in batch mode, define the scripting symbol BATCH_MODE. This will replace all yield return WaitForEndOfFrame operations with yield return null.


<< Welcome to the Dialogue System for Unity! | Import & Export >>