Page 1 of 1
Saving the Location Table
Posted: Fri Mar 24, 2017 10:58 pm
by Franky
Hi! Great system, love it. Easy to work with.
I want to save everything in the location table too, though.
I guess I could run the lua engine with a foreach loop, iterate through everything in the table and save it to a string, but that's more than a bit of a hassle and I'm not sure what would be the best way to go about that.
Is there any way to just include the location table in the PersistentDataManager.GetSaveData() and PersistentDataManager.ApplySaveData()?
Re: Saving the Location Table
Posted: Sat Mar 25, 2017 8:58 am
by Tony Li
Hi,
In the next version, I'll add an option to include all Location data. In the meantime, you'll need to assign a delegate to
PersistentDataManager.GetCustomSaveData.
Here's an example scene that saves Location data:
SaveLocationTableExample_2017-03-25.unitypackage
It uses this script. You can just drop this script into your project and add it to the Dialogue Manager.
Code: Select all
using UnityEngine;
using System.Text;
using PixelCrushers.DialogueSystem;
public class SaveLocationTable : MonoBehaviour
{
public bool debug = false;
void Awake()
{
PersistentDataManager.GetCustomSaveData = AppendLocationData;
}
private string AppendLocationData()
{
var sb = new StringBuilder();
try
{
var locationTable = Lua.Run("return Location").AsTable;
if (locationTable == null)
{
if (DialogueDebug.LogErrors) Debug.LogError("Dialogue System: Couldn't save Lua Location[] table.");
return string.Empty;
}
foreach (var title in locationTable.Keys)
{
var fields = locationTable[title.ToString()] as LuaTableWrapper;
sb.AppendFormat("Location[\"{0}\"]=", new System.Object[] { DialogueLua.StringToTableIndex(title) });
AppendFields(sb, fields);
}
}
catch (System.Exception e)
{
Debug.LogError("Dialogue System: Failed to save Lua Location[] data: " + e.Message);
}
if (debug) Debug.Log("Dialogue System: Saving this Location info: " + sb.ToString());
return sb.ToString();
}
void AppendFields(StringBuilder sb, LuaTableWrapper fields)
{
sb.Append("{");
try
{
if (fields != null)
{
foreach (var key in fields.Keys)
{
var value = fields[key.ToString()];
sb.AppendFormat("{0}={1}, ", new System.Object[] { DialogueLua.StringToTableIndex(key), GetFieldValueString(value) });
}
}
}
finally
{
sb.Append("}; ");
}
}
string GetFieldValueString(object o)
{
if (o == null) return "nil";
System.Type type = o.GetType();
if (type == typeof(string))
{
return string.Format("\"{0}\"", new System.Object[] { DialogueLua.DoubleQuotesToSingle(o.ToString().Replace("\n", "\\n")) });
}
else if (type == typeof(bool))
{
return o.ToString().ToLower();
}
else
{
return o.ToString();
}
}
}