- Home /
How can I save data to a text/json file and read it back and then assign the values back to the variables ?
The main goal is to be able to save and load the conversations List content to a file and read it back to the conversations List so it will be like it is now in the Inspector. The values should be assigned to the right variables and it should look like in the Inspector in the screenshot at the bottom.
I'm also not sure if I should use json or just simple text file and how to do it.
I have this script with a List type Conversation name conversations. I want to store the conversations to a file and to be able to read it back using two buttons for saving and for loading.
This is the script with the two methods for saving and loading :
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
[ExecuteInEditMode]
public class DialogueTrigger : MonoBehaviour
{
public List<Conversation> conversations = new List<Conversation>();
[HideInInspector]
public int dialogueNum = 0;
[HideInInspector]
public int dialogueIndex = 0;
private bool triggered = false;
private List<Dialogue> oldDialogue;
private bool activateButton = false;
public void TriggerDialogue(int dialogueIndex)
{
this.dialogueIndex = dialogueIndex;
if (conversations.Count > 0 &&
conversations[dialogueIndex].Dialogues.Count > 0)
{
if (triggered == false)
{
if (FindObjectOfType<DialogueManager>() != null)
{
FindObjectOfType<DialogueManager>().StartDialogue(conversations[dialogueIndex].Dialogues[dialogueNum]);
dialogueNum += 1;
}
triggered = true;
}
}
}
private void Update()
{
ButtonActivation();
if (DialogueManager.dialogueEnded == true)
{
if (dialogueNum == conversations[dialogueIndex].Dialogues.Count)
{
return;
}
else
{
FindObjectOfType<DialogueManager>().StartDialogue(conversations[dialogueIndex].Dialogues[dialogueNum]);
DialogueManager.dialogueEnded = false;
dialogueNum += 1;
}
}
}
public bool ActivateButton()
{
return activateButton;
}
private void ButtonActivation()
{
if (ConversationsChecks() == true)
{
foreach (string sentence in conversations[dialogueIndex].Dialogues[dialogueNum].sentences)
{
if (sentence != "")
{
activateButton = true;
}
else
{
activateButton = false;
}
}
}
else
{
activateButton = false;
}
}
public void SaveConversations()
{
string jsonTransform = JsonHelper.ToJson(conversations.ToArray(), true);
File.WriteAllText(@"d:\json.txt", jsonTransform);
}
public void LoadConversations()
{
//string jsonTransform = File.ReadAllText(@"d:\json.txt");
//conversations = JsonHelper.FromJson<Conversation>(jsonTransform);
}
private bool ConversationsChecks()
{
bool IsConversationsReady = false;
if (conversations.Count > 0 &&
conversations[dialogueIndex].Dialogues.Count > 0 &&
conversations[dialogueIndex].Dialogues[dialogueNum].sentences.Count > 0 &&
conversations[dialogueIndex].Dialogues[dialogueNum].name != "" &&
conversations[dialogueIndex].name != "")
{
IsConversationsReady = true;
}
else
{
IsConversationsReady = false;
}
return IsConversationsReady;
}
}
This is the buttons script for now only for the saving :
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(DialogueTrigger))]
public class SaveConversationsButton : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
DialogueTrigger dialoguetrigger = (DialogueTrigger)target;
if(dialoguetrigger.ActivateButton() == true)
{
GUI.enabled = true;
}
else
{
GUI.enabled = false;
}
if (GUILayout.Button("Save Conversations"))
{
dialoguetrigger.SaveConversations();
}
}
}
When I click the Save Conversations button it's writing the conversations List content to a file. This is how the file content looks like after saved:
{
"Items": [
{
"name": "Conversation 1",
"Dialogues": [
{
"name": "Dialogue 1",
"sentences": [
"Hello World",
"It's my time to make a magic"
]
}
]
},
{
"name": "The openning scene",
"Dialogues": [
{
"name": "NAVI",
"sentences": [
"Hello to you",
"Lets hide quick"
]
},
{
"name": "PLAYER",
"sentences": [
"I'm the player now lets go"
]
}
]
}
]
}
But now how do I read it back and assign it back to the conversation List ? So it will looks like as before in the Inspector ?
This is a screenshot of how it looks like in the Inspector :
Answer by Bunny83 · Apr 12, 2019 at 11:50 AM
All you need to do is this:
public void LoadConversations()
{
string jsonTransform = File.ReadAllText(@"d:\json.txt");
conversations = new List<Conversation>(JsonHelper.FromJson<Conversation>(jsonTransform));
}
Alternatively without creating a new list you can do
public void LoadConversations()
{
string jsonTransform = File.ReadAllText(@"d:\json.txt");
conversations.Clear();
conversations.AddRange(JsonHelper.FromJson<Conversation>(jsonTransform));
}
Note when calling LoadConversations() from an editor script you may need to ensure to register a proper Undo action in order to actually get the changes serialized inside Unity. Though since you don't have a load button at the moment this code is generally missing in your script.
Working great I added the Load button :
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(DialogueTrigger))]
public class SaveConversationsButton : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
DialogueTrigger dialoguetrigger = (DialogueTrigger)target;
if(dialoguetrigger.ActivateButton() == true)
{
GUI.enabled = true;
}
else
{
GUI.enabled = false;
}
if (GUILayout.Button("Save Conversations"))
{
dialoguetrigger.SaveConversations();
}
GUI.enabled = true;
if(GUILayout.Button("Load Conversations"))
{
dialoguetrigger.LoadConversations();
}
}
}
And the trigger script in the load method :
public void LoadConversations()
{
string jsonTransform = File.ReadAllText(@"d:\json.txt");
conversations.Clear();
conversations.AddRange(JsonHelper.FromJson<Conversation>(jsonTransform));
}
Now how do I use and where to add the register a proper Undo action ?
Well it should probably just be:
if(GUILayout.Button("Load Conversations"))
{
Undo.RecordObject(dialoguetrigger, "Loaded conversations from JSON");
dialoguetrigger.LoadConversations();
}
Answer by Patel-Sagar · Apr 12, 2019 at 10:47 AM
Check this out if this fulfils your requirement. It is added by Unity.
https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity https://docs.unity3d.com/Manual/JSONSerialization.html