Esempio n. 1
0
 /// <summary>
 /// "Follows" a dialogue entry and returns its full conversation state. This method updates
 /// the Lua environment (marking the entry as visited). If includeLinks is <c>true</c>,
 /// it evaluates all links from the dialogue entry and records valid links in the state.
 /// </summary>
 /// <returns>
 /// The state representing the dialogue entry.
 /// </returns>
 /// <param name='entry'>
 /// The dialogue entry to "follow."
 /// </param>
 /// <param name='includeLinks'>
 /// If <c>true</c>, records all links from the dialogue entry whose conditions are true.
 /// </param>
 public ConversationState GetState(DialogueEntry entry, bool includeLinks)
 {
     if (entry != null)
     {
         DialogueLua.MarkDialogueEntryDisplayed(entry);
         SetDialogTable(entry.conversationID);
         Lua.Run(entry.userScript, DialogueDebug.LogInfo, allowLuaExceptions);
         CharacterInfo actorInfo     = GetCharacterInfo(entry.ActorID);
         CharacterInfo listenerInfo  = GetCharacterInfo(entry.ConversantID);
         FormattedText formattedText = FormattedText.Parse(entry.SubtitleText, database.emphasisSettings);
         CheckSequenceField(entry);
         string          entrytag     = database.GetEntrytag(entry.conversationID, entry.id, entrytagFormat);
         Subtitle        subtitle     = new Subtitle(actorInfo, listenerInfo, formattedText, entry.Sequence, entry.ResponseMenuSequence, entry, entrytag);
         List <Response> npcResponses = new List <Response>();
         List <Response> pcResponses  = new List <Response>();
         if (includeLinks)
         {
             EvaluateLinks(entry, npcResponses, pcResponses, new List <DialogueEntry>());
         }
         return(new ConversationState(subtitle, npcResponses.ToArray(), pcResponses.ToArray(), entry.isGroup));
     }
     else
     {
         return(null);
     }
 }
Esempio n. 2
0
 public static void AddToConversationTable(List <Conversation> conversations, List <DialogueDatabase> loadedDatabases)
 {
     foreach (Conversation conversation in conversations)
     {
         if (!DialogueDatabase.Contains(loadedDatabases, conversation))
         {
             SetFields(string.Format("Conversation[{0}]", new System.Object[] { conversation.id }), conversation.fields, "Dialog = {}");
         }
     }
     if (!includeSimStatus)
     {
         return;
     }
     foreach (Conversation conversation in conversations)
     {
         StringBuilder sb = new StringBuilder();
         sb.AppendFormat("Conversation[{0}].Dialog = {{ ", new System.Object[] { conversation.id });
         foreach (DialogueEntry dialogueEntry in conversation.dialogueEntries)
         {
             // [NOTE] To reduce Lua memory use, we only record SimStatus of dialogue entries:
             sb.AppendFormat("[{0}]={{SimStatus=\"Untouched\"}},", new System.Object[] { dialogueEntry.id });
         }
         sb.Append('}');
         bool luaExceptionOccurred = false;
         try {
             Lua.Run(sb.ToString(), false, true);
         } catch (System.Exception) {
             luaExceptionOccurred = true;
         }
         if (luaExceptionOccurred && DialogueDebug.LogErrors)
         {
             Debug.LogError(string.Format("{0}: LuaExceptions above indicate a dialogue database inconsistency. Is an invalid conversation ID recorded in a dialogue entry?", new System.Object[] { DialogueDebug.Prefix }));
         }
     }
 }
Esempio n. 3
0
 /// <summary>
 /// Appends the actor table to a saved-game string.
 /// </summary>
 private static void AppendActorData(StringBuilder sb)
 {
     try {
         LuaTableWrapper actorTable = Lua.Run("return Actor").AsTable;
         if (actorTable == null)
         {
             if (DialogueDebug.LogErrors)
             {
                 Debug.LogError(string.Format("{0}: Persistent Data Manager couldn't access Lua Actor[] table", new System.Object[] { DialogueDebug.Prefix }));
             }
             return;
         }
         foreach (var key in actorTable.Keys)
         {
             LuaTableWrapper fields = actorTable[key.ToString()] as LuaTableWrapper;
             sb.AppendFormat("Actor[\"{0}\"]={1}", new System.Object[] { DialogueLua.StringToTableIndex(key), '{' });
             try {
                 AppendActorFieldData(sb, fields);
             } finally {
                 sb.Append("}; ");
             }
         }
     } catch (System.Exception e) {
         Debug.LogError(string.Format("{0}: GetSaveData() failed to get actor data: {1}", new System.Object[] { DialogueDebug.Prefix, e.Message }));
     }
 }
Esempio n. 4
0
 /// <summary>
 /// Appends the user variable table to a (saved-game) string.
 /// </summary>
 public static void AppendVariableData(StringBuilder sb)
 {
     try
     {
         LuaTableWrapper variableTable = Lua.Run("return Variable").asTable;
         if (variableTable == null)
         {
             if (DialogueDebug.logErrors)
             {
                 Debug.LogError(string.Format("{0}: Persistent Data Manager couldn't access Lua Variable[] table", new System.Object[] { DialogueDebug.Prefix }));
             }
             return;
         }
         sb.Append("Variable={");
         var first = true;
         foreach (var key in variableTable.keys)
         {
             if (!first)
             {
                 sb.Append(", ");
             }
             first = false;
             var value = variableTable[key.ToString()];
             sb.AppendFormat("{0}={1}", new System.Object[] { GetFieldKeyString(key), GetFieldValueString(value) });
         }
         sb.Append("}; ");
     }
     catch (System.Exception e)
     {
         Debug.LogError(string.Format("{0}: GetSaveData() failed to get variable data: {1}", new System.Object[] { DialogueDebug.Prefix, e.Message }));
     }
 }
Esempio n. 5
0
 /// <summary>
 /// Deletes a quest from the Lua Item[] table. Use this method if you want to remove a quest entirely.
 /// If you just want to set the state of a quest, use SetQuestState.
 /// </summary>
 /// <param name='title'>
 /// Title of the quest.
 /// </param>
 /// <example>
 /// QuestLog.RemoveQuest("Kill 5 Rats");
 /// </example>
 public static void DeleteQuest(string title)
 {
     if (!string.IsNullOrEmpty(title))
     {
         Lua.Run(string.Format("Item[\"{0}\"] = nil", new System.Object[] { DialogueLua.StringToTableIndex(title) }), DialogueDebug.LogInfo);
     }
 }
Esempio n. 6
0
 /// <summary>
 /// Sets the value of a field in a Lua table element.
 /// </summary>
 /// <param name="table">Table name.</param>
 /// <param name="element">Name of an element in the table.</param>
 /// <param name="field">Name of a field in the element.</param>
 /// <param name="value">The value to set the field to.</param>
 public static void SetTableField(string table, string element, string field, object value)
 {
     if (DoesTableElementExist(table, element))
     {
         bool   isString   = (value != null) && (value.GetType() == typeof(string));
         string valueInLua = isString
                                 ? DoubleQuotesToSingle((string)value)
                                         : ((value != null) ? value.ToString().ToLower() : "nil");
         Lua.Run(string.Format("{0}[\"{1}\"].{2} = {3}{4}{3}",
                               new System.Object[] { table,
                                                     StringToTableIndex(element),
                                                     StringToTableIndex(field),
                                                     (isString ? "\"" : string.Empty),
                                                     valueInLua }),
                 DialogueDebug.LogInfo);
     }
     else
     {
         if (DialogueDebug.LogWarnings)
         {
             Debug.LogWarning(string.Format("{0}: Entry \"{1}\" doesn't exist in table {2}[]; can't set {3} to {4}",
                                            new System.Object[] { DialogueDebug.Prefix, StringToTableIndex(element), table, field, value }));
         }
     }
 }
 /// <summary>
 /// "Follows" a dialogue entry and returns its full conversation state. This method updates
 /// the Lua environment (marking the entry as visited). If includeLinks is <c>true</c>,
 /// it evaluates all links from the dialogue entry and records valid links in the state.
 /// </summary>
 /// <returns>The state.</returns>
 /// <param name="entry">The dialogue entry to "follow."</param>
 /// <param name="includeLinks">If set to <c>true</c> records all links from the dialogue entry whose conditions are true.</param>
 /// <param name="stopAtFirstValid">If set to <c>true</c> ,stops including at the first valid link.</param>
 /// <param name="skipExecution">IF set to <c>true</c>, doesn't run the Lua Script or OnExecute event.</param>
 public ConversationState GetState(DialogueEntry entry, bool includeLinks, bool stopAtFirstValid = false, bool skipExecution = false)
 {
     if (entry != null)
     {
         DialogueManager.instance.SendMessage(DialogueSystemMessages.OnPrepareConversationLine, entry, SendMessageOptions.DontRequireReceiver);
         DialogueLua.MarkDialogueEntryDisplayed(entry);
         Lua.Run("thisID = " + entry.id);
         SetDialogTable(entry.conversationID);
         if (!skipExecution)
         {
             Lua.Run(entry.userScript, DialogueDebug.logInfo, m_allowLuaExceptions);
             entry.onExecute.Invoke();
         }
         CharacterInfo actorInfo     = GetCharacterInfo(entry.ActorID);
         CharacterInfo listenerInfo  = GetCharacterInfo(entry.ConversantID);
         FormattedText formattedText = FormattedText.Parse(entry.subtitleText, m_database.emphasisSettings);
         CheckSequenceField(entry);
         string          entrytag     = m_database.GetEntrytag(entry.conversationID, entry.id, m_entrytagFormat);
         Subtitle        subtitle     = new Subtitle(actorInfo, listenerInfo, formattedText, entry.currentSequence, entry.currentResponseMenuSequence, entry, entrytag);
         List <Response> npcResponses = new List <Response>();
         List <Response> pcResponses  = new List <Response>();
         if (includeLinks)
         {
             EvaluateLinks(entry, npcResponses, pcResponses, new List <DialogueEntry>(), stopAtFirstValid);
         }
         return(new ConversationState(subtitle, npcResponses.ToArray(), pcResponses.ToArray(), entry.isGroup));
     }
     else
     {
         return(null);
     }
 }
Esempio n. 8
0
 private static Lua.Result SafeGetLuaResult(string luaCode)
 {
     try {
         return(Lua.Run(luaCode, DialogueDebug.LogInfo));
     } catch (System.Exception) {
         return(Lua.NoResult);
     }
 }
 private void DoLuaAction()
 {
     if (string.IsNullOrEmpty(luaCode))
     {
         return;
     }
     Lua.Run(luaCode, DialogueDebug.logInfo);
 }
Esempio n. 10
0
 public void DoAction(LuaAction action, Transform actor)
 {
     if (action == null)
     {
         return;
     }
     Lua.Run(action.luaCode, debugLua);
 }
Esempio n. 11
0
 protected virtual void DoLuaAction()
 {
     if (string.IsNullOrEmpty(luaCode))
     {
         return;
     }
     Lua.Run(luaCode, DialogueDebug.logInfo);
 }
Esempio n. 12
0
 private void SetDialogTable(int newConversationID)
 {
     if (currentConversationID != newConversationID)
     {
         currentConversationID = newConversationID;
         Lua.Run(string.Format("Dialog = Conversation[{0}].Dialog", new System.Object[] { newConversationID }));
     }
 }
 public void DoAction(LuaAction action, Transform actor)
 {
     if (action == null)
     {
         return;
     }
     Lua.Run(action.luaCode, debugLua);
     DialogueManager.SendUpdateTracker();
 }
Esempio n. 14
0
 private static void AddToVariableTable(List <Variable> variables, List <DialogueDatabase> loadedDatabases)
 {
     foreach (Variable variable in variables)
     {
         if (!DialogueDatabase.Contains(loadedDatabases, variable))
         {
             Lua.Run(string.Format("Variable[\"{0}\"] = {1}", new System.Object[] { StringToTableIndex(variable.Name), ValueAsString(variable.Type, variable.InitialValue) }), DialogueDebug.LogInfo);
         }
     }
 }
Esempio n. 15
0
        /// <summary>
        /// Call this method to manually run the action.
        /// </summary>
        public void Fire()
        {
            // Quest:
            if (!string.IsNullOrEmpty(questName))
            {
                QuestLog.SetQuestState(questName, questState);
            }

            // Lua:
            if (!string.IsNullOrEmpty(luaCode))
            {
                Lua.Run(luaCode, DialogueDebug.logInfo);
                DialogueManager.CheckAlerts();
            }

            // Sequence:
            if (!string.IsNullOrEmpty(sequence))
            {
                DialogueManager.PlaySequence(sequence);
            }

            // Alert:
            if (!string.IsNullOrEmpty(alertMessage))
            {
                string localizedAlertMessage;
                if ((textTable != null) && textTable.HasFieldTextForLanguage(alertMessage, Localization.GetCurrentLanguageID(textTable)))
                {
                    localizedAlertMessage = textTable.GetFieldTextForLanguage(alertMessage, Localization.GetCurrentLanguageID(textTable));
                }
                else
                {
                    localizedAlertMessage = DialogueManager.GetLocalizedText(alertMessage);
                }
                DialogueManager.ShowAlert(localizedAlertMessage);
            }

            // Send Messages:
            foreach (var sma in sendMessages)
            {
                if (sma.gameObject != null && !string.IsNullOrEmpty(sma.message))
                {
                    sma.gameObject.SendMessage(sma.message, sma.parameter, SendMessageOptions.DontRequireReceiver);
                }
            }

            DialogueManager.SendUpdateTracker();

            if (once)
            {
                StopObserving();
                enabled = false;
            }
        }
Esempio n. 16
0
 /// <summary>
 /// Adds a quest to the Lua Item[] table.
 /// </summary>
 /// <param name='title'>
 /// Title of the quest.
 /// </param>
 /// <param name='description'>
 /// Description of the quest.
 /// </param>
 /// <param name='state'>
 /// Quest state.
 /// </param>
 /// <example>
 /// QuestLog.AddQuest("Kill 5 Rats", "The baker asked me to bring 5 rat corpses.", QuestState.Unassigned);
 /// </example>
 public static void AddQuest(string title, string description, QuestState state)
 {
     if (!string.IsNullOrEmpty(title))
     {
         Lua.Run(string.Format("Item[\"{0}\"] = {{ Name = \"{1}\", Description = \"{2}\", State = \"{3}\" }}",
                               new System.Object[] { DialogueLua.StringToTableIndex(title),
                                                     DialogueLua.DoubleQuotesToSingle(title),
                                                     DialogueLua.DoubleQuotesToSingle(description),
                                                     StateToString(state) }),
                 DialogueDebug.LogInfo);
     }
 }
Esempio n. 17
0
        /// <summary>
        /// Gets an array of all quests matching the specified state bitmask.
        /// </summary>
        /// <returns>
        /// The titles of all quests matching the specified state bitmask.
        /// </returns>
        /// <param name='flags'>
        /// A bitmask of QuestState values.
        /// </param>
        /// <example>
        /// string[] completedQuests = QuestLog.GetAllQuests( QuestState.Success | QuestState.Failure );
        /// </example>
        public static string[] GetAllQuests(QuestState flags)
        {
            List <string>   titles    = new List <string>();
            LuaTableWrapper itemTable = Lua.Run("return Item").AsTable;

            if (!itemTable.IsValid)
            {
                if (DialogueDebug.LogWarnings)
                {
                    Debug.LogWarning(string.Format("{0}: Quest Log couldn't access Lua Item[] table. Has the Dialogue Manager loaded a database yet?", new System.Object[] { DialogueDebug.Prefix }));
                }
                return(titles.ToArray());
            }
            foreach (LuaTableWrapper fields in itemTable.Values)
            {
                string title  = null;
                bool   isItem = false;
                try {
                    object titleObject = fields["Name"];
                    title  = (titleObject != null) ? titleObject.ToString() : string.Empty;
                    isItem = false;
                    object isItemObject = fields["Is_Item"];
                    if (isItemObject != null)
                    {
                        if (isItemObject.GetType() == typeof(bool))
                        {
                            isItem = (bool)isItemObject;
                        }
                        else
                        {
                            isItem = Tools.StringToBool(isItemObject.ToString());
                        }
                    }
                } catch {}
                if (!isItem)
                {
                    if (string.IsNullOrEmpty(title))
                    {
                        if (DialogueDebug.LogWarnings)
                        {
                            Debug.LogWarning(string.Format("{0}: A quest title (item name in Item[] table) is null or empty", new System.Object[] { DialogueDebug.Prefix }));
                        }
                    }
                    else if (IsQuestInStateMask(title, flags))
                    {
                        titles.Add(title);
                    }
                }
            }
            titles.Sort();
            return(titles.ToArray());
        }
Esempio n. 18
0
        public override void ApplyDataImmediate()
        {
            // Immediately restore Lua in case other scripts'
            // Start() methods need to read values from it.
            var data = SaveSystem.currentSavedGameData.GetData(key);

            if (string.IsNullOrEmpty(data))
            {
                return;
            }
            Lua.Run(data, DialogueDebug.logInfo, false);
            m_appliedImmediate = true;
        }
Esempio n. 19
0
        /// <summary>
        /// Instructs the Dialogue System to add any missing variables that are in the master
        /// database but not in Lua.
        /// </summary>
        public static void InitializeNewVariablesFromDatabase()
        {
            try
            {
                LuaTableWrapper variableTable = Lua.Run("return Variable").asTable;
                if (variableTable == null)
                {
                    if (DialogueDebug.logErrors)
                    {
                        Debug.LogError(string.Format("{0}: Persistent Data Manager couldn't access Lua Variable[] table", new System.Object[] { DialogueDebug.Prefix }));
                    }
                    return;
                }
                var database = DialogueManager.masterDatabase;
                if (database == null)
                {
                    return;
                }
                var inLua = new HashSet <string>(variableTable.keys);
                for (int i = 0; i < database.variables.Count; i++)
                {
                    var variable      = database.variables[i];
                    var variableName  = variable.Name;
                    var variableIndex = DialogueLua.StringToTableIndex(variableName);
                    if (!inLua.Contains(variableIndex))
                    {
                        switch (variable.Type)
                        {
                        case FieldType.Boolean:
                            DialogueLua.SetVariable(variableName, variable.InitialBoolValue);
                            break;

                        case FieldType.Actor:
                        case FieldType.Item:
                        case FieldType.Location:
                        case FieldType.Number:
                            DialogueLua.SetVariable(variableName, variable.InitialFloatValue);
                            break;

                        default:
                            DialogueLua.SetVariable(variableName, variable.InitialValue);
                            break;
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError(string.Format("{0}: InitializeNewVariablesFromDatabase() failed to get variable data: {1}", new System.Object[] { DialogueDebug.Prefix, e.Message }));
            }
        }
        public void Fire()
        {
            if (DialogueDebug.logInfo)
            {
                Debug.Log(string.Format("{0}: Setting quest '{1}' state to '{2}'", new System.Object[] { DialogueDebug.Prefix, questName, QuestLog.StateToString(questState) }));
            }

            // Quest states:
            if (!string.IsNullOrEmpty(questName))
            {
                if (setQuestState)
                {
                    QuestLog.SetQuestState(questName, questState);
                }
                if (setQuestEntryState)
                {
                    QuestLog.SetQuestEntryState(questName, questEntryNumber, questEntryState);
                }
            }

            // Lua:
            if (!string.IsNullOrEmpty(luaCode))
            {
                Lua.Run(luaCode, DialogueDebug.logInfo);
            }

            // Alert:
            if (!string.IsNullOrEmpty(alertMessage))
            {
                string localizedAlertMessage = alertMessage;
                if ((localizedTextTable != null) && localizedTextTable.ContainsField(alertMessage))
                {
                    localizedAlertMessage = localizedTextTable[alertMessage];
                }
                DialogueManager.ShowAlert(localizedAlertMessage);
            }

            // Send Messages:
            foreach (var sma in sendMessages)
            {
                if (sma.gameObject != null && !string.IsNullOrEmpty(sma.message))
                {
                    sma.gameObject.SendMessage(sma.message, sma.parameter, SendMessageOptions.DontRequireReceiver);
                }
            }

            DialogueManager.SendUpdateTracker();

            // Once?
            DestroyIfOnce();
        }
Esempio n. 21
0
        /// <summary>
        /// Checks the watch item and calls the delegate if the Lua expression changed.
        /// </summary>
        public void Check()
        {
            Lua.Result result   = Lua.Run(luaExpression);
            string     newValue = result.asString;

            if (!string.Equals(m_currentValue, newValue))
            {
                m_currentValue = newValue;
                if (luaChanged != null)
                {
                    luaChanged(this, result);
                }
            }
        }
Esempio n. 22
0
 /// <summary>
 /// Appends all conversation fields to a saved-game string. Note that this doesn't
 /// append the fields inside each dialogue entry, just the fields in the conversation
 /// objects themselves.
 /// </summary>
 private static void AppendAllConversationFields(StringBuilder sb)
 {
     try
     {
         LuaTableWrapper conversationTable = Lua.Run("return Conversation").asTable;
         if (conversationTable == null)
         {
             if (DialogueDebug.logErrors)
             {
                 Debug.LogError(string.Format("{0}: Persistent Data Manager couldn't access Lua Conversation[] table", new System.Object[] { DialogueDebug.Prefix }));
             }
             return;
         }
         foreach (var convIndex in conversationTable.keys) // Loop through conversations:
         {
             LuaTableWrapper fields = Lua.Run("return Conversation[" + convIndex + "]").asTable;
             if (fields == null)
             {
                 continue;
             }
             sb.Append("Conversation[" + convIndex + "]={");
             try
             {
                 var first = true;
                 foreach (var key in fields.keys)
                 {
                     if (string.Equals(key, "Dialog"))
                     {
                         continue;
                     }
                     if (!first)
                     {
                         sb.Append(", ");
                     }
                     first = false;
                     var value = fields[key.ToString()];
                     sb.AppendFormat("{0}={1}", new System.Object[] { GetFieldKeyString(key), GetFieldValueString(value) });
                 }
             }
             finally
             {
                 sb.Append("}; ");
             }
         }
     }
     catch (System.Exception e)
     {
         Debug.LogError(string.Format("{0}: GetSaveData() failed to get conversation data: {1}", new System.Object[] { DialogueDebug.Prefix, e.Message }));
     }
 }
Esempio n. 23
0
 /// <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 }));
     }
 }
Esempio n. 24
0
        public void UpdateMembership()
        {
            var newIdValue = Lua.Run("return " + groupId, DialogueDebug.logInfo, false).asString;

            if (string.Equals(newIdValue, "nil"))
            {
                newIdValue = groupId;
            }
            if (newIdValue != m_currentIdValue)
            {
                BarkGroupManager.instance.RemoveFromGroup(m_currentIdValue, this);
                BarkGroupManager.instance.AddToGroup(newIdValue, this);
                m_currentIdValue = newIdValue;
            }
        }
Esempio n. 25
0
 private static bool IsAssetInTable(string assetTableName, string assetName)
 {
     LuaInterface.LuaTable table = Lua.Run(string.Format("return {0}", new System.Object[] { assetTableName })).AsLuaTable;
     if (table != null)
     {
         foreach (string key in table.Keys)
         {
             if (string.Equals(key, assetName))
             {
                 return(true);
             }
         }
     }
     return(false);
 }
Esempio n. 26
0
 /// <summary>
 /// Adds the assets defined in a DialogueDatabase to the Chat Mapper tables. Doesn't add
 /// assets that are contained in loadedDatabases. Runs the global user script if defined.
 /// </summary>
 /// <param name='database'>
 /// The DialogueDatabase containing assets to add.
 /// </param>
 /// <param name='loadedDatabases'>
 /// List of databases that have already been loaded and added to Lua.
 /// </param>
 public static void AddChatMapperVariables(DialogueDatabase database, List <DialogueDatabase> loadedDatabases)
 {
     if (database != null)
     {
         AddToTable <Actor>("Actor", database.actors, loadedDatabases);
         AddToTable <Item>("Item", database.items, loadedDatabases);
         AddToTable <Location>("Location", database.locations, loadedDatabases);
         AddToVariableTable(database.variables, loadedDatabases);
         AddToConversationTable(database.conversations, loadedDatabases);
         if (!string.IsNullOrEmpty(database.globalUserScript))
         {
             Lua.Run(database.globalUserScript, DialogueDebug.LogInfo);
         }
     }
 }
Esempio n. 27
0
 public override void ApplyDataImmediate()
 {
     if (!m_changingScenes)
     {
         // If loading a saved game, immediately restore Lua in case other scripts'
         // Start() methods need to read values from it.
         var data = SaveSystem.currentSavedGameData.GetData(key);
         if (string.IsNullOrEmpty(data))
         {
             return;
         }
         Lua.Run(data, DialogueDebug.logInfo, false);
     }
     m_changingScenes = false;
 }
Esempio n. 28
0
 /// <summary>
 /// Loads a saved game by applying a saved-game string.
 /// </summary>
 /// <param name='saveData'>
 /// A saved-game string previously returned by GetSaveData().
 /// </param>
 /// <param name='databaseResetOptions'>
 /// Database reset options.
 /// </param>
 public static void ApplySaveData(string saveData, DatabaseResetOptions databaseResetOptions = DatabaseResetOptions.KeepAllLoaded)
 {
     if (DialogueDebug.LogInfo)
     {
         Debug.Log(string.Format("{0}: Resetting Lua environment.", new System.Object[] { DialogueDebug.Prefix }));
     }
     DialogueManager.ResetDatabase(databaseResetOptions);
     if (DialogueDebug.LogInfo)
     {
         Debug.Log(string.Format("{0}: Updating Lua environment with saved data.", new System.Object[] { DialogueDebug.Prefix }));
     }
     Lua.Run(saveData, DialogueDebug.LogInfo);
     RefreshRelationshipAndStatusTablesFromLua();
     Apply();
 }
Esempio n. 29
0
        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);
            }
        }
Esempio n. 30
0
 private static void MarkDialogueEntry(DialogueEntry dialogueEntry, string status)
 {
     if (includeSimStatus && (dialogueEntry != null))
     {
         bool luaExceptionOccurred = false;
         try {
             Lua.Run(string.Format("Conversation[{0}].Dialog[{1}].SimStatus = \"{2}\"", new System.Object[] { dialogueEntry.conversationID, dialogueEntry.id, status }), false, true);
         } catch (System.Exception) {
             luaExceptionOccurred = true;
         }
         if (luaExceptionOccurred && DialogueDebug.LogErrors)
         {
             Debug.LogError(string.Format("{0}: The Lua exception above indicates a dialogue database inconsistency. Is an invalid conversation ID recorded in a dialogue entry? Is the database loaded?", new System.Object[] { DialogueDebug.Prefix }));
         }
     }
 }