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;
}
}