我一直在学习 this 的教程视频。
教程源代码可以在here找到...
我有一个问题,我的 Json 数据都存储在 1 行中,
我希望数据在单个对象数据中换行
这里是 Json 教程的代码
Actor 文件
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;
}
保存数据文件
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);
}
}
JsonUtility.ToJson
有两个重载功能:
public static string ToJson(object obj);
public static string ToJson(object obj, bool prettyPrint);
使用第二个并将 true
传递给它。它将格式化输出以提高可读性,使 json 分隔成行。
只需将 string json = JsonUtility.ToJson(actors);
替换为 string json = JsonUtility.ToJson(actors, true);
如果您对结果不满意,请使用 Newtonsoft.Json对于 Unity 并像这样格式化 json:
string json = JsonConvert.SerializeObject(actors);
string newLineJson = JValue.Parse(json).ToString(Formatting.Indented);
我是一名优秀的程序员,十分优秀!