// This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using System.Collections.Generic;
using UnityEngine;
namespace Fungus
{
///
/// A single line of dialog
///
[System.Serializable]
public class NarrativeLogEntry
{
[SerializeField] public string name;
[SerializeField] public string text;
}
///
/// Serializable object to store Narrative Lines
///
[System.Serializable]
public class NarrativeData
{
public List entries = new List();
}
///
/// Controls dialog history
///
public class NarrativeLog : MonoBehaviour
{
///
/// NarrativeAdded signal. Sent when a line is added.
///
public event NarrativeAddedHandler OnNarrativeAdded;
public delegate void NarrativeAddedHandler(NarrativeLogEntry data);
public void DoNarrativeAdded(NarrativeLogEntry data)
{
if (OnNarrativeAdded != null)
{
OnNarrativeAdded(data);
}
}
///
/// Signal sent when log history is cleared or loaded
///
public System.Action OnNarrativeLogClear;
public void DoNarrativeCleared()
{
if (OnNarrativeLogClear != null)
{
OnNarrativeLogClear();
}
}
NarrativeData history;
protected virtual void Awake()
{
history = new NarrativeData();
DoNarrativeCleared();
}
protected virtual void OnEnable()
{
WriterSignals.OnWriterState += OnWriterState;
}
protected virtual void OnDisable()
{
WriterSignals.OnWriterState -= OnWriterState;
}
protected virtual void OnWriterState(Writer writer, WriterState writerState)
{
if (writerState == WriterState.End)
{
var sd = SayDialog.GetSayDialog();
if (sd != null)
{
NarrativeLogEntry entry = new NarrativeLogEntry()
{
name = sd.NameText,
text = sd.StoryText
};
AddLine(entry);
}
}
}
#region Public Methods
///
/// Add a line of dialog to the Narrative Log
///
public void AddLine(NarrativeLogEntry entry)
{
history.entries.Add(entry);
DoNarrativeAdded(entry);
}
///
/// Clear all lines of the narrative log
/// Usually used on restart
///
public void Clear()
{
history.entries.Clear();
DoNarrativeCleared();
}
///
/// Convert history into Json for saving in SaveData
///
///
public string GetJsonHistory()
{
string jsonText = JsonUtility.ToJson(history, true);
return jsonText;
}
///
/// Show previous lines for display purposes
///
///
public string GetPrettyHistory(bool previousOnly = false)
{
string output = "\n ";
int count;
count = previousOnly ? history.entries.Count - 1 : history.entries.Count;
for (int i = 0; i < count; i++)
{
output += "" + history.entries[i].name + "\n";
output += history.entries[i].text + "\n\n";
}
return output;
}
///
/// Load History from Json
///
///
public void LoadHistory(string narrativeData)
{
if (narrativeData == null)
{
Debug.LogError("Failed to decode History save data item");
return;
}
history = JsonUtility.FromJson(narrativeData);
DoNarrativeCleared();
}
#endregion
}
}