Reputation: 55
I been follow the tutorial from this video.
The tutorial source code can be found at here...
I have a problem of my Json data all been stored in 1 single line,
I want the data break into new line for single object data
Here the code for the Json tutorial
Actor file
using UnityEngine;
using System.Collections;
using System;
public class Actor : MonoBehaviour {
public ActorData data = new ActorData();
public string name = "Tile";
string newline = "\n";
public void StoreData()
{
data.name = name;
data.pos = transform.position;
}
public void LoadData()
{
name = data.name;
transform.position = data.pos;
}
public void ApplyData()
{
SaveData.AddActorData(data);
}
void OnEnable()
{
SaveData.OnLoaded += LoadData;
SaveData.OnBeforeSave += StoreData;
SaveData.OnBeforeSave += ApplyData;
}
void OnDisable()
{
SaveData.OnLoaded -= LoadData;
SaveData.OnBeforeSave -= StoreData;
SaveData.OnBeforeSave -= ApplyData;
}
}
[Serializable]
public class ActorData
{
public string name;
public Vector2 pos;
}
save data file
using UnityEngine;
using System.Collections;
using System.Xml.Serialization;
using System.IO;
public class SaveData
{
public static ActorContainer actorContainer = new ActorContainer();
public delegate void SerializeAction();
public static event SerializeAction OnLoaded;
public static event SerializeAction OnBeforeSave;
public static void Load(string path)
{
actorContainer = LoadActors(path);
foreach (ActorData data in actorContainer.actors)
{
GameController.CreateActor(data, GameController.playerPath,
data.pos, Quaternion.identity);
}
OnLoaded();
ClearActorList();
}
public static void Save(string path, ActorContainer actors)
{
OnBeforeSave();
//ClearSave(path);
SaveActors(path, actors);
ClearActorList();
}
public static void AddActorData(ActorData data)
{
actorContainer.actors.Add(data);
}
public static void ClearActorList()
{
actorContainer.actors.Clear();
}
private static ActorContainer LoadActors(string path)
{
string json = File.ReadAllText(path);
return JsonUtility.FromJson<ActorContainer>(json);
}
private static void SaveActors(string path, ActorContainer actors)
{
string json = JsonUtility.ToJson(actors);
StreamWriter sw = File.CreateText(path);
sw.Close();
File.WriteAllText(path, json);
}
}
Upvotes: 1
Views: 3924
Reputation: 125295
There are two overloads for the JsonUtility.ToJson
function:
public static string ToJson(object obj);
public static string ToJson(object obj, bool prettyPrint);
Use the second one and pass true
to it. It will format the output for readability making the json separated into lines.
Just replace string json = JsonUtility.ToJson(actors);
with string json = JsonUtility.ToJson(actors, true);
If you are not satisfied with the result, use Newtonsoft.Json for Unity and format the json like this:
string json = JsonConvert.SerializeObject(actors);
string newLineJson = JValue.Parse(json).ToString(Formatting.Indented);
Upvotes: 4