Before this, I saved only one instance of the class in Json, and everything worked. Now when I try to save the whole array, nothing works for me. Please don’t advise me to switch to some Newtonsoft. Everywhere they say that JsonUtility can save arrays. Tell me, maybe there is an error in my script?
Here is code:
using System.Collections;
using System.IO;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
public class JsonSaveSystem : MonoBehaviour
{
public List<GameObject> obj;
[SerializeField] private Inventory[] objs;
[SerializeField] private List<possave> pos;
private string path;
possave ps;
void Start()
{
while(obj.Count > pos.Count)
{
pos.Add(ps);
}
path = Path.Combine(Application.persistentDataPath, "data.json");
Load();
}
void Update()
{
//Debug.Log(JsonUtility.ToJson(pos[0]));
if(obj.Count > pos.Count)
{
pos.Add(ps);
}
}
public void Load()
{
if(File.Exists(path))
{
pos = JsonUtility.FromJson<List<possave>>(File.ReadAllText(path));
for(int i = 0; i < objs.Length; i++)
{
for(int k = 0; k < obj.Count; k++)
{
if(objs[i].ID == pos[k].ID)
{
Destroy(obj[k]);
obj[k] = Instantiate(objs[i].obj, new Vector3(pos[k].x, pos[k].y, pos[k].z), Quaternion.identity);
}
}
}
}
else
{
File.Create(path);
}
}
public void Save()
{
for (int i = 0; i < obj.Count; i++)
{
pos[i].x = obj[i].transform.position.x;
pos[i].y = obj[i].transform.position.y;
pos[i].z = obj[i].transform.position.z;
pos[i].ID = obj[i].GetComponent<Takeobjectec>().obj.ID;
File.WriteAllText(path, JsonUtility.ToJson(pos));
}
}
}
[Serializable]
public class possave
{
public float x, y, z;
public string ID;
}
I tried to save everything using JsonSerializer, but Unity gave me the error: error CS0122: ‘JsonSerializer’ is inaccessible due to its protection level. I wrote using System.Text.Json at the beginning of the script, so that wasn’t the issue. If JsonSerializer needs something else, and this is the only way to save an array, please tell me what it needs.