I have a static generic class which is used to load and save Data. I don’t have any compilation error, but the system doesn’t save or load. My project is on Unity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public static class DataManager
{
public static void Save<T>(T data, string path, string name)
{
path = Application.persistentDataPath + "/SaveData" + path;
if (!Directory.Exists(path))
{
Debug.Log("Create New Directory");
Directory.CreateDirectory(path);
}
path = path + "/" + name + ".txt";
Debug.Log("Save : "+path);
string json = JsonUtility.ToJson(data, true);
File.WriteAllText(path, json);
}
public static T Load<T>(string path, string name) where T : Savable, new()
{
path = Application.persistentDataPath + "/SaveData" + path + "/" + name + ".txt";
Debug.Log("Load : "+path);
T data = new T();
if (Directory.Exists(path))
{
Debug.Log("Data Exist (Load)");
string json = File.ReadAllText(path);
data = JsonUtility.FromJson<T>(json);
}
else
{
Debug.Log("Data Don't Exist (Load)");
data.Name = name;
}
return data;
}
}
I put several Debug.Log() in the programme to find the problem, but I don’t find anything.
I als put a Debug.Log() just before the save and just after the save with the data it contain.
As I saw in the Log, the first load is normal if we consider we don’t have any data. (The value after the name of the object are the value in the object.)
When the save happen the object possess the value after modification and the path is the same. It doesn’t find any directory so it create a new directory.
When I load a second time, it doesn’t find the data and use the default data again.
I need the data to be able to load properly.
2
Answers
The solution was found, I needed to use File.Exists instead of Directory.Exists to verify if the data exist.
Because in the
Load
methodpath
is a file path but you are usingDirectory.Exists
to check if the file exists, it will always return false, you should useFile.Exists
instead.