Exemplo n.º 1
0
    public static SaveFile.Content ReadFromFile(string name)
    {
        string file = string.Format("{0}/{1}.{2}", Application.persistentDataPath, name, SaveFile.fileExtension);

        SaveFile.Content result = null;

        if (File.Exists(file))
        {
            string content = File.ReadAllText(file);
            if (string.IsNullOrEmpty(content))
            {
                Debug.LogError("The Save File is invalid, the file is empty.");
                return(SaveFile.GetNewFileContent());
            }

            try
            {
                content = SaveFile.DecryptIfNeeded(content);

                result = JsonUtility.FromJson <SaveFile.Content>(content);
                Debug.LogFormat("Save File file found. Path: {0}", file);
            }
            catch (Exception)
            {
                Debug.LogError("The Save File is invalid, unable to extract data, a new one will be created.");
                result = SaveFile.GetNewFileContent();
            }

            try
            {
                File.WriteAllText(string.Format("{0}/{1}.{2}.bak", Application.persistentDataPath, name, SaveFile.fileExtension), result.ToJson(true));
                //Debug.Log("A backup has been created.");
            }
            catch (Exception ex)
            {
                Debug.LogErrorFormat("Unable to create a backup.", ex.ToString());
            }
        }
        else
        {
            Debug.LogError("The Save File doesn't exist, a new one will be created.");
            result = SaveFile.GetNewFileContent();
        }

        return(result);
    }