我一直关注this视频中的教程。
可以在here ...
找到教程源代码我的问题是我的Json数据全部存储在一行中,
我想将数据分成单行对象数据的新行
这里是Json教程的代码
演员档案
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);
}
}
答案 0 :(得分:3)
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);
如果您对结果不满意,请对Unity使用Newtonsoft.Json并像这样格式化json:
string json = JsonConvert.SerializeObject(actors);
string newLineJson = JValue.Parse(json).ToString(Formatting.Indented);