Hello everyone I’m trying to do Save Load System with Json.
The codes im using are below. And the problem is When i click Save Button There is nothing in the Json text file.
public List<Transform> Transforms;
public void Save()
{
Vector3[] positions = new Vector3[Transforms.Count];
for (int i = 0; i < Transforms.Count; i++)
{
positions _= Transforms*.localPosition;*_
Debug.Log($“position {i}: {positions*}”); // only adding this line* }
string json = JsonUtility.ToJson(positions); Debug.Log($“json: {json}”); // and this File.WriteAllText(Application.dataPath + “/save.txt”, json); } public void Load() { if (File.Exists(Application.dataPath + “/save.txt”)) { string savestring = File.ReadAllText(Application.dataPath + “/save.txt”); Vector3[] positions = JsonUtility.FromJson<Vector3[]>(savestring); for (int i = 0; i < Transforms.Count; i++) { Transforms_.localPosition = positions*; } } }*_
As I mentioned in the comment above, Unity’s JsonUtility does not support arrays as root objects. The root object has to be a serializable object. So you have to do something like this:
[System.Serializable]
public class SaveData
{
public List<Vector3> positions = new List<Vector3>();
}
public void Save()
{
SaveData data = new SaveData();
for (int i = 0; i < Transforms.Count; i++)
{
data.positions.Add(Transforms*.localPosition);*
} string json = JsonUtility.ToJson(data); File.WriteAllText(Application.dataPath + “/save.txt”, json); } public void Load() { if (File.Exists(Application.dataPath + “/save.txt”)) { string savestring = File.ReadAllText(Application.dataPath + “/save.txt”); SaveData data = JsonUtility.FromJson(savestring); for (int i = 0; i < Transforms.Count; i++) { Transforms_.localPosition = data.positions*; } } } An alternative to Unity’s JsonUtility would be either to use the Newtonsoft JSON.NET library. As far as I know it has a surrogate provider in order to serialize Vector3 values directly. Another alternative would be my [SimpleJSON framework][1]. It’s not an object mapper but just a parser. So you can simply access the json data in a generic way. You only need the SimpleJSON.cs file as well as the SimpleJSONUnity.cs file which is an extension file that gives you easy conversion support for most common Unity primitive types. [1]: https://github.com/Bunny83/SimpleJSON*_