0

I have this code below. Why in my ReadFile is me logging (and also my file) saying the array is empty. I call readFile first and the file doesn't exist. Then I call writeFile and it writes an empty array. Sorry I am not great at c#.

public class GameData : MonoBehaviour
{

    string saveFile;
    CarsUnlocked[] carsUnlocked = new CarsUnlocked[3];

    void Awake()
    {
        saveFile = Application.persistentDataPath + "/gamedata.json";
        readFile();
    }

    public void readFile()
    {
        if (File.Exists(saveFile))
        {
            string fileContents = File.ReadAllText(saveFile);
            carsUnlocked = JsonUtility.FromJson<CarsUnlocked[]>(fileContents);
        } else {
            carsUnlocked[0] = new CarsUnlocked(1,2,3,true);
            carsUnlocked[1] = new CarsUnlocked(1,2,3,true);
        }
    }

    public void writeFile()
    {
        Debug.Log(carsUnlocked);
        string jsonString = JsonUtility.ToJson(carsUnlocked);
        File.WriteAllText(saveFile, jsonString);
    }
}


public class CarsUnlocked : MonoBehaviour
{
    public int car;
    public int levelNeeded;
    public int moneyNeeded;
    public bool unlocked = false;   

    public CarsUnlocked(int carX, int levelNeededX, int moneyNeededX, bool unlockedX)
    {
        car = carX;
        levelNeeded = levelNeededX;
        moneyNeeded = moneyNeededX;
        unlocked = unlockedX;
    }   
}
MomasVII
  • 4,641
  • 5
  • 35
  • 52
  • Did you debug the code to see what is stored in `jsonString ` before you write it to the file? – UnholySheep Nov 17 '22 at 21:15
  • 2
    *"Similarly, passing an array to this method will not produce a JSON array containing each element, but an object containing the public fields of the array object itself (of which there are none)."* - from the official docs (https://docs.unity3d.com/ScriptReference/JsonUtility.ToJson.html) – UnholySheep Nov 17 '22 at 21:17
  • Use `NewtonSoft` instead of `JsonUtility`. Makes your life much easier. – CorrieJanse Nov 18 '22 at 02:22
  • First of all remove the `: MonoBehaviour` from the `CarsUnlocked` class ... it doesn't look like it should be one and it is basically "forbidden" to create instances of those using `new` or `FromJson` .... further the `JsonUtility` desn't support direct deserialization of `XXX[]` – derHugo Nov 18 '22 at 07:32

0 Answers0