public virtual bool IsQuestVisible(string questTitle) { return(!checkVisibleField || Lua.IsTrue("Quest[\"" + DialogueLua.StringToTableIndex(questTitle) + "\"].Visible ~= false")); }
/// <summary> /// Checks if a Lua variable "Mute" is <c>true</c>. /// </summary> /// <returns><c>true</c> if audio is muted; otherwise, <c>false</c>.</returns> public static bool IsAudioMuted() { return(DialogueLua.GetVariable("Mute").asBool); }
private static string GetFieldKeyString(string key) { key = DialogueLua.StringToTableIndex(key); return(matchValidVarName.IsMatch(key) ? key : ("[\"" + key + "\"]")); }
/// <summary> /// When loading a game, load the dialogue entry records and resume the conversation. /// </summary> public virtual void OnApplyPersistentData() { if (DontLoadInThisScene()) { Debug.Log("OnApplyPersistentData Dont Load in this scene: " + SceneManager.GetActiveScene().buildIndex); } if (DontLoadInThisScene()) { return; } records.Clear(); if (!DialogueLua.DoesVariableExist(currentDialogueEntryRecords)) { return; } StopAllCoroutines(); // Load dialogue entry records: var s = DialogueLua.GetVariable(currentDialogueEntryRecords).AsString; if (Debug.isDebugBuild) { Debug.Log("TextlineDialogueUI.OnApplyPersistentData: Restoring current conversation from " + currentDialogueEntryRecords + ": " + s); } var ints = s.Split(';'); var numRecords = Tools.StringToInt(ints[0]); for (int i = 0; i < numRecords; i++) { var conversationID = Tools.StringToInt(ints[1 + i * 2]); var entryID = Tools.StringToInt(ints[2 + i * 2]); records.Add(new DialogueEntryRecord(conversationID, entryID)); } // If we have records, resume the conversation: if (records.Count == 0) { return; } var lastRecord = records[records.Count - 1]; if (lastRecord.conversationID >= 0 && lastRecord.entryID > 0) { UnityEngine.UI.Button lastContinueButton = null; try { // Resume conversation: //if (dontRepeatLastSequence) isLoadingGame = true; isLoadingGame = true; var conversation = DialogueManager.MasterDatabase.GetConversation(lastRecord.conversationID); var actorName = DialogueLua.GetVariable(currentConversationActor).AsString; var conversantName = DialogueLua.GetVariable(currentConversationConversant).AsString; var actor = GameObject.Find(actorName); var conversant = GameObject.Find(conversantName); var actorTransform = (actor != null) ? actor.transform : null; var conversantTransform = (conversant != null) ? conversant.transform : null; if (Debug.isDebugBuild) { Debug.Log("Resuming '" + conversation.Title + "' at entry " + lastRecord.entryID); } DialogueManager.StopConversation(); var lastEntry = DialogueManager.MasterDatabase.GetDialogueEntry(lastRecord.conversationID, lastRecord.entryID); var originalSequence = lastEntry.Sequence; // Handle last entry's sequence differently if end entry. npcPreDelaySettings.CopyTo(npcPreDelaySettingsCopy); pcPreDelaySettings.CopyTo(pcPreDelaySettingsCopy); npcPreDelaySettings.basedOnTextLength = false; npcPreDelaySettings.additionalSeconds = 0; pcPreDelaySettings.basedOnTextLength = false; pcPreDelaySettings.additionalSeconds = 0; var isEndEntry = lastEntry.Sequence.Contains("WaitForMessage(Forever)") || lastEntry.outgoingLinks.Count == 0; if (isEndEntry) { if (!lastEntry.Sequence.Contains("WaitForMessage(Forever)")) { lastEntry.Sequence = "WaitForMessage(Forever); " + lastEntry.Sequence; } } else if (dontRepeatLastSequence) { lastEntry.Sequence = "None()"; } else { lastEntry.Sequence = "Delay(0.1)"; } skipNextRecord = true; isInPreDelay = false; DialogueManager.StartConversation(conversation.Title, actorTransform, conversantTransform, lastRecord.entryID); lastContinueButton = continueButton; lastEntry.Sequence = originalSequence; npcPreDelaySettingsCopy.CopyTo(npcPreDelaySettings); pcPreDelaySettingsCopy.CopyTo(pcPreDelaySettings); // Populate UI with previous records: var lastInstance = (instantiatedMessages.Count > 0) ? instantiatedMessages[instantiatedMessages.Count - 1] : null; instantiatedMessages.Remove(lastInstance); DestroyInstantiatedMessages(); for (int i = 0; i < records.Count - 1; i++) { var entry = DialogueManager.MasterDatabase.GetDialogueEntry(records[i].conversationID, records[i].entryID); var speakerInfo = DialogueManager.ConversationModel.GetCharacterInfo(entry.ActorID); var listenerInfo = DialogueManager.ConversationModel.GetCharacterInfo(entry.ConversantID); var formattedText = FormattedText.Parse(entry.currentDialogueText, DialogueManager.MasterDatabase.emphasisSettings); var subtitle = new Subtitle(speakerInfo, listenerInfo, null, formattedText, "None()", entry.ResponseMenuSequence, entry); AddMessage(subtitle); } if (lastInstance != null) { instantiatedMessages.Add(lastInstance); lastInstance.transform.SetAsLastSibling(); } } finally { isLoadingGame = false; scrollRect.verticalNormalizedPosition = 0; continueButton = lastContinueButton; if (shouldShowContinueButton && lastContinueButton != null) { lastContinueButton.gameObject.SetActive(true); } } } ScrollToBottom(); }
private string ApplyScriptWizard() { try { StringBuilder sb = new StringBuilder(); if (append && !string.IsNullOrEmpty(savedLuaCode)) { sb.AppendFormat("{0};\n", savedLuaCode); } string endText = (scriptItems.Count > 1) ? ";\n" : string.Empty; for (int i = 0; i < scriptItems.Count; i++) { var item = scriptItems[i]; if (item.resourceType == ScriptWizardResourceType.Quest) { // Quest: string questName = GetWizardQuestName(questNames, item.questNamesIndex); if (item.netSetMode == NetSetMode.NetSet) { sb.Append("Net"); } sb.AppendFormat("SetQuestState(\"{0}\", \"{1}\")", questName, QuestLog.StateToString(item.questState)); } else if (item.resourceType == ScriptWizardResourceType.QuestEntry) { // Quest Entry: string questName = GetWizardQuestName(complexQuestNames, item.questNamesIndex); if (item.netSetMode == NetSetMode.NetSet) { sb.Append("Net"); } sb.AppendFormat("SetQuestEntryState(\"{0}\", {1}, \"{2}\")", questName, item.questEntryIndex + 1, QuestLog.StateToString(item.questState)); } else if (item.resourceType == ScriptWizardResourceType.Variable) { // Variable: string variableName = (0 <= item.variableNamesIndex && item.variableNamesIndex < variableNames.Length) ? variableNames[item.variableNamesIndex] : "Alert"; switch (GetWizardVariableType(item.variableNamesIndex)) { case FieldType.Boolean: if (item.netSetMode == NetSetMode.NetSet) { sb.AppendFormat("NetSetBool(\"{0}\", {1})", DialogueLua.StringToTableIndex(variableName), (item.booleanValue == BooleanType.True) ? "true" : "false"); } else { sb.AppendFormat("Variable[\"{0}\"] = {1}", DialogueLua.StringToTableIndex(variableName), (item.booleanValue == BooleanType.True) ? "true" : "false"); } break; case FieldType.Number: if (item.netSetMode == NetSetMode.NetSet) { switch (item.valueSetMode) { case ValueSetMode.To: sb.AppendFormat("NetSetNumber(\"{0}\", {1})", DialogueLua.StringToTableIndex(variableName), item.floatValue); break; case ValueSetMode.Add: sb.AppendFormat("NetSetNumber(\"{0}\", Variable[\"{0}\"] + {1})", DialogueLua.StringToTableIndex(variableName), item.floatValue); break; case ValueSetMode.Subtract: sb.AppendFormat("NetSetNumber(\"{0}\", Variable[\"{0}\"] - {1})", DialogueLua.StringToTableIndex(variableName), item.floatValue); break; } } else { switch (item.valueSetMode) { case ValueSetMode.To: sb.AppendFormat("Variable[\"{0}\"] = {1}", DialogueLua.StringToTableIndex(variableName), item.floatValue); break; case ValueSetMode.Add: sb.AppendFormat("Variable[\"{0}\"] = Variable[\"{0}\"] + {1}", DialogueLua.StringToTableIndex(variableName), item.floatValue); break; case ValueSetMode.Subtract: sb.AppendFormat("Variable[\"{0}\"] = Variable[\"{0}\"] - {1}", DialogueLua.StringToTableIndex(variableName), item.floatValue); break; } } break; default: if (item.netSetMode == NetSetMode.NetSet) { sb.AppendFormat("NetSetString(\"{0}\", \"{1}\")", DialogueLua.StringToTableIndex(variableName), item.stringValue); } else { sb.AppendFormat("Variable[\"{0}\"] = \"{1}\"", DialogueLua.StringToTableIndex(variableName), item.stringValue); } break; } } else if (item.resourceType == ScriptWizardResourceType.Actor) { // Actor: if (item.actorNamesIndex < actorNames.Length) { var actorName = actorNames[item.actorNamesIndex]; var actorFieldName = actorFieldNames[item.actorFieldIndex]; var fieldType = GetWizardActorFieldType(item.actorFieldIndex); AppendFormat(sb, "Actor", actorName, actorFieldName, fieldType, item); } } else if (item.resourceType == ScriptWizardResourceType.Item) { // Item: if (item.itemNamesIndex < itemNames.Length) { var itemName = itemNames[item.itemNamesIndex]; var itemFieldName = itemFieldNames[item.itemFieldIndex]; var fieldType = GetWizardItemFieldType(item.itemFieldIndex); AppendFormat(sb, "Item", itemName, itemFieldName, fieldType, item); } } else if (item.resourceType == ScriptWizardResourceType.Location) { // Location: if (item.locationNamesIndex < locationNames.Length) { var locationName = locationNames[item.locationNamesIndex]; var locationFieldName = locationFieldNames[item.locationFieldIndex]; var fieldType = GetWizardLocationFieldType(item.locationFieldIndex); AppendFormat(sb, "Location", locationName, locationFieldName, fieldType, item); } } else if (item.resourceType == ScriptWizardResourceType.SimStatus) { // SimStatus: sb.AppendFormat("Dialog[{0}].SimStatus = \"{1}\"", item.simStatusID, item.simStatusType); } else if (item.resourceType == ScriptWizardResourceType.Alert) { // Custom: sb.Append("ShowAlert(\"" + item.stringValue.Replace("\"", "\\\"") + "\")"); } else if (item.resourceType == ScriptWizardResourceType.Custom) { // Custom: sb.Append(item.stringValue); } if (i < (scriptItems.Count - 1)) { sb.AppendFormat(endText); } } return(sb.ToString()); } catch (Exception e) { Debug.LogError(string.Format("{0}: Internal error building script: {1}", DialogueDebug.Prefix, e.Message)); return(savedLuaCode); } }
private void EvaluateLinksAtPriority(ConditionPriority priority, DialogueEntry entry, List <Response> npcResponses, List <Response> pcResponses, List <DialogueEntry> visited, bool stopAtFirstValid = false) { if (entry != null) { for (int ol = 0; ol < entry.outgoingLinks.Count; ol++) { var link = entry.outgoingLinks[ol]; DialogueEntry destinationEntry = m_database.GetDialogueEntry(link); if ((destinationEntry != null) && (/*(destinationEntry.conditionPriority == priority) ||*/ (link.priority == priority))) // Note: Only observe link priority. Why does Chat Mapper even have conditionPriority? { CharacterType characterType = m_database.GetCharacterType(destinationEntry.ActorID); Lua.Run("thisID = " + destinationEntry.id); bool isValid = Lua.IsTrue(destinationEntry.conditionsString, DialogueDebug.logInfo, m_allowLuaExceptions) && ((isDialogueEntryValid == null) || isDialogueEntryValid(destinationEntry)); if (isValid || (m_includeInvalidEntries && (characterType == CharacterType.PC))) { // Condition is true (or blank), so add this link: if (destinationEntry.isGroup) { // For groups, evaluate their links (after running the group node's Lua code and OnExecute() event): if (DialogueDebug.logInfo) { Debug.Log(string.Format("{0}: Add Group ({1}): ID={2}:{3} '{4}' ({5})", new System.Object[] { DialogueDebug.Prefix, GetActorName(m_database.GetActor(destinationEntry.ActorID)), link.destinationConversationID, link.destinationDialogueID, destinationEntry.Title, isValid })); } Lua.Run(destinationEntry.userScript, DialogueDebug.logInfo, m_allowLuaExceptions); destinationEntry.onExecute.Invoke(); for (int i = (int)ConditionPriority.High; i >= 0; i--) { int originalResponseCount = npcResponses.Count + pcResponses.Count;; EvaluateLinksAtPriority((ConditionPriority)i, destinationEntry, npcResponses, pcResponses, visited); if ((npcResponses.Count + pcResponses.Count) > originalResponseCount) { break; } } } else { // For regular entries, just add them: if (DialogueDebug.logInfo) { Debug.Log(string.Format("{0}: Add Link ({1}): ID={2}:{3} '{4}' ({5})", new System.Object[] { DialogueDebug.Prefix, GetActorName(m_database.GetActor(destinationEntry.ActorID)), link.destinationConversationID, link.destinationDialogueID, GetLinkText(characterType, destinationEntry), isValid })); } if (characterType == CharacterType.NPC) { // Add NPC response: npcResponses.Add(new Response(FormattedText.Parse(destinationEntry.subtitleText, m_database.emphasisSettings), destinationEntry, isValid)); } else { // Add PC response, wrapping old responses in em tags if specified: string text = destinationEntry.responseButtonText; if (m_emTagForOldResponses != EmTag.None) { string simStatus = Lua.Run(string.Format("return Conversation[{0}].Dialog[{1}].SimStatus", new System.Object[] { destinationEntry.conversationID, destinationEntry.id })).asString; bool isOldResponse = string.Equals(simStatus, "WasDisplayed"); if (isOldResponse) { text = string.Format("[em{0}]{1}[/em{0}]", (int)m_emTagForOldResponses, text); } } if (m_emTagForInvalidResponses != EmTag.None) { if (!isValid) { text = string.Format("[em{0}]{1}[/em{0}]", (int)m_emTagForInvalidResponses, text); } } pcResponses.Add(new Response(FormattedText.Parse(text, m_database.emphasisSettings), destinationEntry, isValid)); DialogueLua.MarkDialogueEntryOffered(destinationEntry); } } if (stopAtFirstValid) { return; } } else { // Condition is false, so block or pass through according to destination entry's setting: if (LinkUtility.IsPassthroughOnFalse(destinationEntry)) { if (DialogueDebug.logInfo) { Debug.Log(string.Format("{0}: Passthrough on False Link ({1}): ID={2}:{3} '{4}' Condition='{5}'", new System.Object[] { DialogueDebug.Prefix, GetActorName(m_database.GetActor(destinationEntry.ActorID)), link.destinationConversationID, link.destinationDialogueID, GetLinkText(characterType, destinationEntry), destinationEntry.conditionsString })); } List <Response> linkNpcResponses = new List <Response>(); List <Response> linkPcResponses = new List <Response>(); EvaluateLinks(destinationEntry, linkNpcResponses, linkPcResponses, visited); npcResponses.AddRange(linkNpcResponses); pcResponses.AddRange(linkPcResponses); } else { if (DialogueDebug.logInfo) { Debug.Log(string.Format("{0}: Block on False Link ({1}): ID={2}:{3} '{4}' Condition='{5}'", new System.Object[] { DialogueDebug.Prefix, GetActorName(m_database.GetActor(destinationEntry.ActorID)), link.destinationConversationID, link.destinationDialogueID, GetLinkText(characterType, destinationEntry), destinationEntry.conditionsString })); } } } } } } }
/// <summary> /// Records the current level in Lua. /// </summary> public virtual void OnRecordPersistentData() { DialogueLua.SetVariable("SavedLevelName", Tools.loadedLevelName); }
public static string SanitizeLevelName(string levelName) { return(DialogueLua.StringToTableIndex(levelName).Replace(".", "_")); }
public virtual void OnConversationLine(Subtitle subtitle) { DialogueLua.SetVariable("CurrentConversationID", subtitle.dialogueEntry.conversationID); DialogueLua.SetVariable("CurrentEntryID", subtitle.dialogueEntry.id); }
public virtual void OnConversationEnd(Transform actor) { DialogueLua.SetVariable("CurrentConversationID", -1); }
/// <summary> /// Instructs the Dialogue System to refresh its internal relationship and status tables /// from the values in the Lua environment. Call this after putting new values in the /// Lua environment, such as when loading a saved game. /// </summary> public static void RefreshRelationshipAndStatusTablesFromLua() { DialogueLua.RefreshStatusTableFromLua(); DialogueLua.RefreshRelationshipTableFromLua(); }
private static void ExpandCompressedSimStatusData() { if (!(includeSimStatus && DialogueManager.instance.includeSimStatus)) { return; } try { var useConversationID = string.IsNullOrEmpty(saveConversationSimStatusWithField); var useEntryID = string.IsNullOrEmpty(saveDialogueEntrySimStatusWithField); var entryDict = new Dictionary <string, DialogueEntry>(); foreach (var conversation in DialogueManager.masterDatabase.conversations) { // If saving dialogue entries' SimStatus with value of a field, make a lookup table: if (!useEntryID) { entryDict.Clear(); for (int i = 0; i < conversation.dialogueEntries.Count; i++) { var entry = conversation.dialogueEntries[i]; var entryFieldValue = Field.LookupValue(entry.fields, saveDialogueEntrySimStatusWithField); if (!entryDict.ContainsKey(entryFieldValue)) { entryDict.Add(entryFieldValue, entry); } } } var sb = new StringBuilder(); string simX; if (useConversationID) { simX = Lua.Run("return Conversation[" + conversation.id + "].SimX").asString; } else { var fieldValue = DialogueLua.StringToTableIndex(conversation.LookupValue(saveConversationSimStatusWithField)); if (string.IsNullOrEmpty(fieldValue)) { fieldValue = conversation.id.ToString(); } simX = Lua.Run("return Variable[\"Conversation_SimX_" + fieldValue + "\"]").asString; } if (string.IsNullOrEmpty(simX) || string.Equals(simX, "nil")) { continue; } var clearSimXCommand = useConversationID ? ("Conversation[" + conversation.id + "].SimX=nil;") : ("Variable[\"Conversation_SimX_" + DialogueLua.StringToTableIndex(conversation.LookupValue(saveConversationSimStatusWithField)) + "\"]=nil;"); sb.Append("Conversation["); sb.Append(conversation.id); sb.Append("].Dialog={}; "); var simXFields = simX.Split(';'); var numFields = simXFields.Length / 2; for (int i = 0; i < numFields; i++) { var simXEntryIDValue = simXFields[2 * i]; string entryID; if (useEntryID) { entryID = simXEntryIDValue; } else { entryID = entryDict.ContainsKey(simXEntryIDValue) ? entryDict[simXEntryIDValue].id.ToString() : "-1"; } var simStatus = CharToSimStatus(simXFields[(2 * i) + 1][0]); sb.Append("Conversation["); sb.Append(conversation.id); sb.Append("].Dialog["); sb.Append(entryID); sb.Append("]={SimStatus='"); sb.Append(simStatus); sb.Append("'}; "); } sb.Append(clearSimXCommand); Lua.Run(sb.ToString()); } } catch (System.Exception e) { Debug.LogError(string.Format("{0}: ApplySaveData() failed to re-expand compressed SimStatus data: {1}", new System.Object[] { DialogueDebug.Prefix, e.Message })); } }
/// <summary> /// Appends the conversation table to a (saved-game) string. To conserve space, only the /// SimStatus is recorded. If includeSimStatus is <c>false</c>, nothing is recorded. /// The exception is if includeAllConversationFields is true. /// </summary> public static void AppendConversationData(StringBuilder sb) { if (includeAllConversationFields || DialogueManager.instance.persistentDataSettings.includeAllConversationFields) { AppendAllConversationFields(sb); } if (!(includeSimStatus && DialogueManager.instance.includeSimStatus)) { return; } try { #if USE_NLUA var useConversationID = string.IsNullOrEmpty(saveConversationSimStatusWithField); var useEntryID = string.IsNullOrEmpty(saveDialogueEntrySimStatusWithField); foreach (var conversation in DialogueManager.MasterDatabase.conversations) { if (useConversationID) { sb.AppendFormat("Conversation[{0}].SimX=\"", conversation.id); } else { var fieldValue = DialogueLua.StringToTableIndex(conversation.LookupValue(saveConversationSimStatusWithField)); if (string.IsNullOrEmpty(fieldValue)) { fieldValue = conversation.id.ToString(); } sb.AppendFormat("Variable[\"Conversation_SimX_{0}\"]=\"", fieldValue); } var dialogTable = Lua.Run("return Conversation[" + conversation.id + "].Dialog").AsLuaTable; var first = true; for (int i = 0; i < conversation.dialogueEntries.Count; i++) { var entry = conversation.dialogueEntries[i]; var entryID = entry.id; var dialogFields = dialogTable[entryID] as NLua.LuaTable; if (dialogFields != null) { if (!first) { sb.Append(";"); } first = false; sb.Append(useEntryID ? entryID.ToString() : Field.LookupValue(entry.fields, saveDialogueEntrySimStatusWithField)); sb.Append(";"); var simStatus = dialogFields["SimStatus"].ToString(); sb.Append(SimStatusToChar(simStatus)); } } sb.Append("\"; "); } #else var useConversationID = string.IsNullOrEmpty(saveConversationSimStatusWithField); var useEntryID = string.IsNullOrEmpty(saveDialogueEntrySimStatusWithField); foreach (var conversation in DialogueManager.masterDatabase.conversations) { if (useConversationID) { sb.AppendFormat("Conversation[{0}].SimX=\"", conversation.id); } else { sb.AppendFormat("Variable[\"Conversation_SimX_{0}\"]=\"", DialogueLua.StringToTableIndex(conversation.LookupValue(saveConversationSimStatusWithField))); } var conversationTable = Lua.Run("return Conversation[" + conversation.id + "]").asTable; var dialogTable = conversationTable.luaTable.GetValue("Dialog") as Language.Lua.LuaTable; var first = true; for (int i = 0; i < conversation.dialogueEntries.Count; i++) { var entry = conversation.dialogueEntries[i]; var entryID = entry.id; var dialogFields = dialogTable.GetValue(entryID) as Language.Lua.LuaTable; if (dialogFields != null) { if (!first) { sb.Append(";"); } first = false; sb.Append(useEntryID ? entryID.ToString() : Field.LookupValue(entry.fields, saveDialogueEntrySimStatusWithField)); sb.Append(";"); var simStatus = dialogFields.GetValue("SimStatus").ToString(); sb.Append(SimStatusToChar(simStatus)); } } sb.Append("\"; "); } #endif } catch (System.Exception e) { Debug.LogError(string.Format("{0}: GetSaveData() failed to get conversation data: {1}", new System.Object[] { DialogueDebug.Prefix, e.Message })); } }
private void MarkDestroyed() { DialogueLua.SetVariable(ActualVariableName, true); }
private IEnumerator LoadLevelFromSaveData(string saveData) { if (DialogueDebug.logInfo) { Debug.Log("Dialogue System: LevelManager: Starting LoadLevelFromSaveData coroutine"); } string levelName = defaultStartingLevel; if (string.IsNullOrEmpty(saveData)) { // If no saveData, reset the database. if (DialogueDebug.logInfo) { Debug.Log("Dialogue System: LevelManager: Save data is empty, so just resetting database"); } DialogueManager.ResetDatabase(DatabaseResetOptions.RevertToDefault); } else { // Put saveData in Lua so we can get Variable["SavedLevelName"]: if (DialogueDebug.logInfo) { Debug.Log("Dialogue System: LevelManager: Applying save data to get value of 'SavedLevelName' variable"); } Lua.Run(saveData, DialogueDebug.logInfo); levelName = DialogueLua.GetVariable("SavedLevelName").asString; if (string.IsNullOrEmpty(levelName) || string.Equals(levelName, "nil")) { levelName = defaultStartingLevel; if (DialogueDebug.logInfo) { Debug.Log("Dialogue System: LevelManager: 'SavedLevelName' isn't defined. Using default level " + levelName); } } else { if (DialogueDebug.logInfo) { Debug.Log("Dialogue System: LevelManager: SavedLevelName = " + levelName); } } } // Load the level: PersistentDataManager.LevelWillBeUnloaded(); if (CanLoadAsync()) { AsyncOperation async = Tools.LoadLevelAsync(levelName); isLoading = true; while (!async.isDone) { yield return(null); } isLoading = false; } else { Tools.LoadLevel(levelName); } // Wait two frames for objects in the level to finish their Start() methods: if (DialogueDebug.logInfo) { Debug.Log("Dialogue System: LevelManager finished loading level " + levelName + ". Waiting 2 frames for scene objects to start."); } yield return(null); yield return(null); // Then apply saveData to the objects: if (!string.IsNullOrEmpty(saveData)) { if (DialogueDebug.logInfo) { Debug.Log("Dialogue System: LevelManager waited 2 frames. Appling save data: " + saveData); } PersistentDataManager.ApplySaveData(saveData); } // Update quest tracker HUD: DialogueManager.SendUpdateTracker(); }
/// <summary> /// Records the current level in Lua. /// </summary> public void OnRecordPersistentData() { DialogueLua.SetVariable("SavedLevelName", Application.loadedLevelName); }
void RpcSetFloat(string variableName, float value) { DialogueLua.SetVariable(variableName, value); }
private string ApplyConditionsWizard() { try { StringBuilder sb = new StringBuilder(); string logicalOperator = GetLogicalOperatorText(conditionsLogicalOperator); var needParens = (conditionItems.Count > 1) || (append && !string.IsNullOrEmpty(savedLuaCode)); openParen = needParens ? "(" : string.Empty; closeParen = needParens ? ")" : string.Empty; if (append && !string.IsNullOrEmpty(savedLuaCode)) { sb.AppendFormat("{0} {1} ", savedLuaCode, logicalOperator); } bool first = true; foreach (ConditionItem item in conditionItems) { if (!first) { sb.AppendFormat(" {0} ", logicalOperator); } first = false; if (item.conditionType == ConditionWizardResourceType.Quest) { // Quest: string questName = GetWizardQuestName(questNames, item.questNamesIndex); //sb.AppendFormat("{0}Quest[\"{1}\"].State {2} \"{3}\"{4}", // openParen, // DialogueLua.StringToTableIndex(questName), // GetWizardEqualityText(item.equalityType), // QuestLog.StateToString(item.questState), // closeParen); sb.AppendFormat("{0}CurrentQuestState(\"{1}\") {2} \"{3}\"{4}", openParen, questName, GetWizardEqualityText(item.equalityType), QuestLog.StateToString(item.questState), closeParen); } else if (item.conditionType == ConditionWizardResourceType.QuestEntry) { // Quest Entry: string questName = GetWizardQuestName(complexQuestNames, item.questNamesIndex); //sb.AppendFormat("{0}Quest[\"{1}\"].Entry_{2}_State {3} \"{4}\"{5}", // openParen, // DialogueLua.StringToTableIndex(questName), // item.questEntryIndex + 1, // GetWizardEqualityText(item.equalityType), // QuestLog.StateToString(item.questState), // closeParen); sb.AppendFormat("{0}CurrentQuestEntryState(\"{1}\", {2}) {3} \"{4}\"{5}", openParen, questName, item.questEntryIndex + 1, GetWizardEqualityText(item.equalityType), QuestLog.StateToString(item.questState), closeParen); } else if (item.conditionType == ConditionWizardResourceType.Variable) { // Variable: string variableName = variableNames[item.variableNamesIndex]; switch (GetWizardVariableType(item.variableNamesIndex)) { case FieldType.Boolean: sb.AppendFormat("{0}Variable[\"{1}\"] {2} {3}{4}", openParen, DialogueLua.StringToTableIndex(variableName), GetWizardEqualityText(item.equalityType), (item.booleanValue == BooleanType.True) ? "true" : "false", closeParen); break; case FieldType.Number: if (item.comparisonType == ComparisonType.Between) { sb.AppendFormat("{0}{3} <= Variable[\"{1}\"] and Variable[\"{1}\"] <= {4}{5}", openParen, DialogueLua.StringToTableIndex(variableName), GetWizardComparisonText(item.comparisonType), item.floatValue, item.floatValue2, closeParen); } else { sb.AppendFormat("{0}Variable[\"{1}\"] {2} {3}{4}", openParen, DialogueLua.StringToTableIndex(variableName), GetWizardComparisonText(item.comparisonType), item.floatValue, closeParen); } break; default: sb.AppendFormat("{0}Variable[\"{1}\"] {2} \"{3}\"{4}", openParen, DialogueLua.StringToTableIndex(variableName), GetWizardEqualityText(item.equalityType), item.stringValue, closeParen); break; } } else if (item.conditionType == ConditionWizardResourceType.Actor) { // Actor: if (item.actorNamesIndex < actorNames.Length) { var actorName = actorNames[item.actorNamesIndex]; var actorField = actorFieldNames[item.actorFieldIndex]; var actorFieldType = GetWizardActorFieldType(item.actorFieldIndex); AppendFormat(sb, "Actor", actorName, actorField, actorFieldType, item); } else { sb.Append("(true)"); } } else if (item.conditionType == ConditionWizardResourceType.Item) { // Item: if (item.itemNamesIndex < itemNames.Length) { var itemName = itemNames[item.itemNamesIndex]; var itemField = itemFieldNames[item.itemFieldIndex]; var itemFieldType = GetWizardItemFieldType(item.itemFieldIndex); AppendFormat(sb, "Item", itemName, itemField, itemFieldType, item); } else { sb.Append("(true)"); } } else if (item.conditionType == ConditionWizardResourceType.Location) { // Location: if (item.locationNamesIndex < locationNames.Length) { var locationName = locationNames[item.locationNamesIndex]; var locationField = locationFieldNames[item.locationFieldIndex]; var locationFieldType = GetWizardLocationFieldType(item.locationFieldIndex); AppendFormat(sb, "Location", locationName, locationField, locationFieldType, item); } else { sb.Append("(true)"); } } else if (item.conditionType == ConditionWizardResourceType.SimStatus) { // SimStatus: string simStatusID = item.simStatusThisID ? "thisID" : item.simStatusID.ToString(); sb.AppendFormat("{0}Dialog[{1}].SimStatus {2} \"{3}\"{4}", openParen, simStatusID, GetWizardEqualityText(item.equalityType), item.simStatusType, closeParen); } else if (item.conditionType == ConditionWizardResourceType.Custom) { // Custom: sb.AppendFormat("{0}{1}{2}", openParen, item.stringValue, closeParen); } } return(sb.ToString()); } catch (Exception e) { Debug.LogError(string.Format("{0}: Internal error building condition: {1}", DialogueDebug.Prefix, e.Message)); return(savedLuaCode); } //-- Moved to AcceptConditionsWizard: currentConditionsWizardEntry = null; }
void RpcSetString(string variableName, string value) { DialogueLua.SetVariable(variableName, value); }
private string ApplyScriptWizard() { try { StringBuilder sb = new StringBuilder(); string endText = (scriptItems.Count > 1) ? ";\n" : string.Empty; for (int i = 0; i < scriptItems.Count; i++) { var item = scriptItems[i]; if (item.resourceType == WizardResourceType.Quest) { // Quest: string questName = GetWizardQuestName(questNames, item.questNamesIndex); sb.AppendFormat("Quest[\"{0}\"].State = \"{1}\"", DialogueLua.StringToTableIndex(questName), QuestLog.StateToString(item.questState)); } else if (item.resourceType == WizardResourceType.QuestEntry) { // Quest Entry: string questName = GetWizardQuestName(complexQuestNames, item.questNamesIndex); sb.AppendFormat("Quest[\"{0}\"].Entry_{1}_State = \"{2}\"", DialogueLua.StringToTableIndex(questName), item.questEntryIndex + 1, QuestLog.StateToString(item.questState)); } else if (item.resourceType == WizardResourceType.Variable) { // Variable: string variableName = variableNames[item.variableNamesIndex]; switch (GetWizardVariableType(item.variableNamesIndex)) { case FieldType.Boolean: sb.AppendFormat("Variable[\"{0}\"] = {1}", DialogueLua.StringToTableIndex(variableName), (item.booleanValue == BooleanType.True) ? "true" : "false"); break; case FieldType.Number: if (item.valueSetMode == ValueSetMode.To) { sb.AppendFormat("Variable[\"{0}\"] = {1}", DialogueLua.StringToTableIndex(variableName), item.floatValue); } else { sb.AppendFormat("Variable[\"{0}\"] = Variable[\"{0}\"] + {1}", DialogueLua.StringToTableIndex(variableName), item.floatValue); } break; default: sb.AppendFormat("Variable[\"{0}\"] = \"{1}\"", DialogueLua.StringToTableIndex(variableName), item.stringValue); break; } } else if (item.resourceType == WizardResourceType.Actor) { // Actor: if (item.actorNamesIndex < actorNames.Length) { var actorName = actorNames[item.actorNamesIndex]; var actorFieldName = actorFieldNames[item.actorFieldIndex]; var fieldType = GetWizardActorFieldType(item.actorFieldIndex); AppendFormat(sb, "Actor", actorName, actorFieldName, fieldType, item); } } else if (item.resourceType == WizardResourceType.Item) { // Item: if (item.itemNamesIndex < itemNames.Length) { var itemName = itemNames[item.itemNamesIndex]; var itemFieldName = itemFieldNames[item.itemFieldIndex]; var fieldType = GetWizardItemFieldType(item.itemFieldIndex); AppendFormat(sb, "Item", itemName, itemFieldName, fieldType, item); } } else if (item.resourceType == WizardResourceType.Location) { // Location: if (item.locationNamesIndex < locationNames.Length) { var locationName = locationNames[item.locationNamesIndex]; var locationFieldName = locationFieldNames[item.locationFieldIndex]; var fieldType = GetWizardLocationFieldType(item.locationFieldIndex); AppendFormat(sb, "Location", locationName, locationFieldName, fieldType, item); } } if (i < (scriptItems.Count - 1)) { sb.AppendFormat(endText); } } return(sb.ToString()); } catch (Exception e) { Debug.LogError(string.Format("{0}: Internal error building script: {1}", DialogueDebug.Prefix, e.Message)); return(savedLuaCode); } }
void RpcSetBool(string variableName, bool value) { DialogueLua.SetVariable(variableName, value); }
/// <summary> /// Removes all loaded databases from the master database and clears the Lua environment. /// </summary> public void Clear() { DialogueLua.InitializeChatMapperVariables(); m_masterDatabase.Clear(); m_loadedDatabases.Clear(); }
/// <summary> /// Appends the item table to a (saved-game) string. /// </summary> public static void AppendItemData(StringBuilder sb) { try { LuaTableWrapper itemTable = Lua.Run("return Item").asTable; if (itemTable == null) { if (DialogueDebug.logErrors) { Debug.LogError(string.Format("{0}: Persistent Data Manager couldn't access Lua Item[] table", new System.Object[] { DialogueDebug.Prefix })); } return; } foreach (var title in itemTable.keys) { LuaTableWrapper fields = itemTable[title.ToString()] as LuaTableWrapper; bool onlySaveQuestData = !includeAllItemData && (DialogueManager.masterDatabase.items.Find(i => string.Equals(DialogueLua.StringToTableIndex(i.Name), title)) != null); if (fields != null) { if (onlySaveQuestData) { // If in the database, just record quest statuses and tracking: foreach (var fieldKey in fields.keys) { string fieldTitle = fieldKey.ToString(); if (fieldTitle.EndsWith("State")) { sb.AppendFormat("Item[\"{0}\"].{1}=\"{2}\"; ", new System.Object[] { DialogueLua.StringToTableIndex(title), (System.Object)fieldTitle, (System.Object)fields[fieldTitle] }); } else if (string.Equals(fieldTitle, "Track")) { sb.AppendFormat("Item[\"{0}\"].Track={1}; ", new System.Object[] { DialogueLua.StringToTableIndex(title), fields[fieldTitle].ToString().ToLower() }); } } } else { // If not in the database, record all fields: sb.AppendFormat("Item[\"{0}\"]=", new System.Object[] { DialogueLua.StringToTableIndex(title) }); AppendFields(sb, fields); } } } } catch (System.Exception e) { Debug.LogError(string.Format("{0}: GetSaveData() failed to get item data: {1}", new System.Object[] { DialogueDebug.Prefix, e.Message })); } }