protected System.Collections.IEnumerator StartSavedConversation(Data data) { var dialogueUI = DialogueManager.dialogueUI as StandardDialogueUI; DialogueManager.StopConversation(); if (dialogueUI != null) { float safeguardTimeout = Time.realtimeSinceStartup + 5f; while (dialogueUI.isOpen && Time.realtimeSinceStartup < safeguardTimeout) { yield return(null); } } var conversationID = data.conversationID; var entryID = data.entryID; var conversation = DialogueManager.masterDatabase.GetConversation(conversationID); var actorName = DialogueLua.GetVariable("CurrentConversationActor").AsString; var conversantName = DialogueLua.GetVariable("CurrentConversationConversant").AsString; if (DialogueDebug.logInfo) { Debug.Log("Dialogue System: ConversationStateSaver is resuming conversation " + conversation.Title + " with actor=" + actorName + " and conversant=" + conversantName + " at entry " + entryID + ".", this); } var actor = string.IsNullOrEmpty(actorName) ? null : GameObject.Find(actorName); var conversant = string.IsNullOrEmpty(conversantName) ? null : GameObject.Find(conversantName); var actorTransform = (actor != null) ? actor.transform : null; var conversantTransform = (conversant != null) ? conversant.transform : null; var ui = DialogueManager.dialogueUI as StandardDialogueUI; if (ui != null) { ui.conversationUIElements.standardSubtitleControls.QueueSavedActorPanelCache(data.actorGOs, data.actorGOPanels, data.actorIDs, data.actorIDPanels); } DialogueManager.StartConversation(conversation.Title, actorTransform, conversantTransform, entryID); }
public virtual void OnApplyPersistentData() { if (!enabled) { return; } var conversationID = DialogueLua.GetVariable("CurrentConversationID").AsInt; var entryID = DialogueLua.GetVariable("CurrentEntryID").AsInt; if (conversationID >= 0 && entryID > 0) { var conversation = DialogueManager.MasterDatabase.GetConversation(conversationID); var actorName = DialogueLua.GetVariable("CurrentConversationActor").AsString; var conversantName = DialogueLua.GetVariable("CurrentConversationConversant").AsString; if (DialogueDebug.logInfo) { Debug.Log("Dialogue System: ConversationStateSaver is resuming conversation " + conversation.Title + " with actor=" + actorName + " and conversant=" + conversantName + " at entry " + entryID + ".", this); } var actor = GameObject.Find(actorName); var conversant = GameObject.Find(conversantName); var actorTransform = (actor != null) ? actor.transform : null; var conversantTransform = (conversant != null) ? conversant.transform : null; DialogueManager.StopConversation(); DialogueManager.StartConversation(conversation.Title, actorTransform, conversantTransform, entryID); } }
public void TryIncrement() { if (!Application.isPlaying) { return; } if (DialogueManager.MasterDatabase == null) { return; } if (!(listenForOnDestroy && condition.IsTrue(null))) { return; } int oldValue = DialogueLua.GetVariable(ActualVariableName).AsInt; int newValue = Mathf.Clamp(oldValue + increment, min, max); DialogueLua.SetVariable(ActualVariableName, newValue); DialogueManager.SendUpdateTracker(); if (!(string.IsNullOrEmpty(alertMessage) || DialogueManager.Instance == null)) { if (Mathf.Approximately(0, alertDuration)) { DialogueManager.ShowAlert(alertMessage); } else { DialogueManager.ShowAlert(alertMessage, alertDuration); } } onIncrement.Invoke(); }
public override void ApplyData(string s) { if (!enabled || string.IsNullOrEmpty(s)) { return; } var data = SaveSystem.Deserialize <Data>(s); if (data == null) { return; } DialogueManager.StopConversation(); var conversationID = data.conversationID; var entryID = data.entryID; var conversation = DialogueManager.masterDatabase.GetConversation(conversationID); var actorName = DialogueLua.GetVariable("CurrentConversationActor").AsString; var conversantName = DialogueLua.GetVariable("CurrentConversationConversant").AsString; if (DialogueDebug.logInfo) { Debug.Log("Dialogue System: ConversationStateSaver is resuming conversation " + conversation.Title + " with actor=" + actorName + " and conversant=" + conversantName + " at entry " + entryID + ".", this); } var actor = string.IsNullOrEmpty(actorName) ? null : GameObject.Find(actorName); var conversant = string.IsNullOrEmpty(conversantName) ? null : GameObject.Find(conversantName); var actorTransform = (actor != null) ? actor.transform : null; var conversantTransform = (conversant != null) ? conversant.transform : null; var ui = DialogueManager.dialogueUI as StandardDialogueUI; if (ui != null) { ui.conversationUIElements.standardSubtitleControls.QueueSavedActorPanelCache(data.actorGOs, data.actorGOPanels, data.actorIDs, data.actorIDPanels); } DialogueManager.StartConversation(conversation.Title, actorTransform, conversantTransform, entryID); }
/// <summary> /// When applying persistent data, check the variable. If it's <c>true</c>, /// the GameObject has been destroyed previously, so destroy it now. /// </summary> public void OnApplyPersistentData() { if (DialogueLua.GetVariable(ActualVariableName).AsBool) { // Before destroying the object, make it think that the level is // being unloaded. This will disable any persistent data scripts // that use OnDestroy, since it's not really being destroyed // during gameplay in this case. gameObject.BroadcastMessage("OnLevelWillBeUnloaded", SendMessageOptions.DontRequireReceiver); Destroy(gameObject); } }
private IEnumerator LoadLevel(string saveData) { string levelName = defaultStartingLevel; if (string.IsNullOrEmpty(saveData)) { // If no saveData, reset the database. DialogueManager.ResetDatabase(DatabaseResetOptions.RevertToDefault); } else { // Put saveData in Lua so we can get Variable["SavedLevelName"]: Lua.Run(saveData, true); levelName = DialogueLua.GetVariable("SavedLevelName").AsString; if (string.IsNullOrEmpty(levelName)) { levelName = defaultStartingLevel; } } // Load the level: PersistentDataManager.LevelWillBeUnloaded(); if (Application.HasProLicense()) { AsyncOperation async = Application.LoadLevelAsync(levelName); IsLoading = true; while (!async.isDone) { yield return(null); } IsLoading = false; } else { Application.LoadLevel(levelName); } // Wait two frames for objects in the level to finish their Start() methods: yield return(null); yield return(null); // Then apply saveData to the objects: if (!string.IsNullOrEmpty(saveData)) { PersistentDataManager.ApplySaveData(saveData); } }
/// <summary> /// When this object is destroyed, increment the counter and update the quest tracker. /// </summary> public void OnDestroy() { if (!listenForOnDestroy) { return; } int oldValue = DialogueLua.GetVariable(ActualVariableName).AsInt; int newValue = Mathf.Clamp(oldValue + increment, min, max); DialogueLua.SetVariable(ActualVariableName, newValue); DialogueManager.SendUpdateTracker(); if (!(string.IsNullOrEmpty(alertMessage) || DialogueManager.Instance == null)) { DialogueManager.ShowAlert(alertMessage); } }
/// <summary> /// Replaces the [autocase=varName] tags with the value of the Lua variable varName, /// capitalized if at the beginning of the string or after end-of-sentence punctuation /// and optional whitespace; lowercase otherwise. /// </summary> /// <param name='text'> /// Text with autocase tags replaced. /// </param> private static void ReplaceAutocaseTags(ref string text) { const string autocaseTagStart = "[autocase="; const int maxReplacements = 100; if (text.Contains(autocaseTagStart)) { // Match "[autocase=" and then anything up to "]": Regex regex = new Regex(@"\[autocase=[^\]]*\]"); int endPosition = text.Length - 1; int numReplacements = 0; // Sanity check to prevent infinite loops in case of bug. while ((endPosition >= 0) && (numReplacements < maxReplacements)) { numReplacements++; int varTagPosition = text.LastIndexOf(autocaseTagStart, endPosition, System.StringComparison.OrdinalIgnoreCase); endPosition = varTagPosition - 1; if (varTagPosition >= 0) { string firstPart = text.Substring(0, varTagPosition); bool capitalize = ShouldCapitalizeNextChar(firstPart); string secondPart = text.Substring(varTagPosition); string secondPartVarReplaced = regex.Replace(secondPart, delegate(Match match) { string varName = match.Value.Substring(10, match.Value.Length - 11).Trim(); // Remove "[autocase=" and "]" try { var variableValue = DialogueLua.GetVariable(varName).asString; if (variableValue.Length > 0) { variableValue = SetCapitalization(capitalize, variableValue); } return(variableValue); } catch (System.Exception) { if (DialogueDebug.logWarnings) { Debug.LogWarning(string.Format("{0}: Failed to get variable: '{1}'", new System.Object[] { DialogueDebug.Prefix, varName })); } return(string.Empty); } }); text = firstPart + secondPartVarReplaced; } } } }
/// <summary> /// Extracts pic tag indices. /// </summary> /// <returns>The pic tag index, or NoPicOverride if no applicable tag is in the text.</returns> /// <param name="tagName">Tag regex (e.g., "[pic=".</param> /// <param name="text">Text.</param> private static int ExtractPicTag(string tagRegex, ref string text) { int index = FormattedText.NoPicOverride; Regex regex = new Regex(tagRegex); text = regex.Replace(text, delegate(Match match) { int startPos = match.Value.IndexOf('=') + 1; string indexString = match.Value.Substring(startPos, match.Value.Length - (startPos + 1)); // Remove "[pic[ac]=" and "]" if (!int.TryParse(indexString, out index)) { index = DialogueLua.GetVariable(indexString).asInt; } return(string.Empty); }); return(index); }
/// <summary> /// When this object is destroyed, increment the counter and update the quest tracker. /// </summary> void OnDestroy() { if (!listenForOnDestroy || string.IsNullOrEmpty(variable)) { return; } int oldValue = DialogueLua.GetVariable(variable).AsInt; int newValue = Mathf.Clamp(oldValue + increment, min, max); DialogueLua.SetVariable(variable, newValue); if (DialogueManager.Instance != null) { DialogueManager.Instance.BroadcastMessage("UpdateTracker", SendMessageOptions.DontRequireReceiver); } if (!string.IsNullOrEmpty(alertMessage)) { DialogueManager.ShowAlert(alertMessage); } }
/// <summary> /// Replaces the [var=varName] tags with the value of the Lua variable varName. /// </summary> /// <param name='text'> /// Text with var tags replaced. /// </param> private static void ReplaceVarTags(ref string text) { const string varTagStart = "[var="; const int maxReplacements = 100; if (text.Contains(varTagStart)) { Regex regex = new Regex(@"\[var=.*\]"); int endPosition = text.Length - 1; int numReplacements = 0; // Sanity check to prevent infinite loops in case of bug. while ((endPosition >= 0) && (numReplacements < maxReplacements)) { numReplacements++; int varTagPosition = text.LastIndexOf(varTagStart, endPosition, System.StringComparison.OrdinalIgnoreCase); endPosition = varTagPosition - 1; if (varTagPosition >= 0) { string firstPart = text.Substring(0, varTagPosition); string secondPart = text.Substring(varTagPosition); string secondPartVarReplaced = regex.Replace(secondPart, delegate(Match match) { string varName = match.Value.Substring(5, match.Value.Length - 6).Trim(); // Remove "[var=" and "]" try { return(DialogueLua.GetVariable(varName).AsString); } catch (System.Exception) { if (DialogueDebug.LogWarnings) { Debug.LogWarning(string.Format("{0}: Failed to get variable: '{1}'", new System.Object[] { DialogueDebug.Prefix, varName })); } return(string.Empty); } }); text = firstPart + secondPartVarReplaced; } } } }
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> /// 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); }
/// <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(); }