Некорректно работает сохранение игры в яндекс играх
Я написал игру на юнити и решил выложить в яндекс игры. Но возникла проблема с сохранениями. При выполнении игры, все сохраняется корректно. Но стоит выйти из игры и зайти обратно - часть сохранений сбрасывается. А именно, data.CardsList и data.AchievementsList (но думаю, проблема идентичная, так что говорю только про data.CardsList). Скажите, пожалуйста, в чем тут заключается проблема? Файл mainMenu (с него начинается игра)
[SerializeField] public double total_breads;
[SerializeField] double breads;
public TMP_Text breadsOutput, profiPerHourOutput;
double profitPerHour;
public int clicksAmount;
NumbersReduction NumRec;
CardsManager CardsManager;
public CardInfo[] RegularCardsList, SpecialCardsList, LegendCardsList;
public CardInfo[][] cardsListsArray;
public TimeBonus tb;
public GameObject effect;
public GameObject button;
public AudioSource audioSource;
DataStructure clientData;
private void Start() {
clientData = SavesJSON.LoadData();
clientData.AplicationWasClosed = false;
audioSource = GetComponent<AudioSource>();
breads = clientData.Breads;
total_breads = clientData.TotalBreads;
clicksAmount = clientData.ClicksAmount;
profitPerHour = clientData.ProfitPerHour;
NumRec = new NumbersReduction();
StartCoroutine(AutoFarm());
}
void Update()
{
if (GameObject.Find("Balance_Value")) breadsOutput.text = NumRec.NumberReduction((int)breads);
if (GameObject.Find("ProfitPerHour_Value")) profiPerHourOutput.text = NumRec.NumberReduction(profitPerHour);
}
void OnDisable()
{
SaveGameData();
}
void OnApplicationQuit()
{
clientData.AplicationWasClosed = true;
SavesJSON.CreateData(clientData);
}
void SaveGameData()
{
clientData.Breads = (int)breads;
clientData.TotalBreads = (int)total_breads;
clientData.ClicksAmount = clicksAmount;
clientData.ProfitPerHour = profitPerHour;
SavesJSON.CreateData(clientData);
}
Файл savesJSON, который отвечает за реализацию сохранений:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.IO;
using YG;
public class DataStructure : ScriptableObject
{
public int Breads { get; set; }
public int TotalBreads { get; set; }
public double ProfitPerHour { get; set; }
public int ClicksAmount { get; set; }
public bool FirstPurchase { get; set; }
public bool UnknowCardBought { get; set; }
public bool AplicationWasClosed { get; set; }
public string LastSession { get; set; }
public double TimeInGame { get; set; }
public List<CardInfo> CardsList { get; set; } = new List<CardInfo>();
public List<AchievementsInfo> AchievementsList { get; set; } = new List<AchievementsInfo>();
}
public class SavesJSON : MonoBehaviour
{
public static void CreateData(DataStructure clientData)
{
DataStructure data = new DataStructure();
// Проверяем, существует ли файл и загружаем данные, если он существует
//if (File.Exists("Assets/Scripts/Saves/datajson.json"))
//{
// string json = File.ReadAllText("Assets/Scripts/Saves/datajson.json");
// data = JsonConvert.DeserializeObject<DataStructure>(json);
//}
//else
//{
// // Если файла нет, создаём новый объект
// data = new DataStructure();
//}
// Обновляем данные
data.Breads = clientData.Breads;
data.TotalBreads = clientData.TotalBreads;
if (clientData.ProfitPerHour > 0) data.ProfitPerHour = clientData.ProfitPerHour;
if (clientData.ClicksAmount > 0) data.ClicksAmount = clientData.ClicksAmount;
if (clientData.FirstPurchase) data.FirstPurchase = clientData.FirstPurchase;
if (clientData.LastSession != null) data.LastSession = clientData.LastSession;
if (clientData.TimeInGame > 0) data.TimeInGame = clientData.TimeInGame;
data.AplicationWasClosed = clientData.AplicationWasClosed;
if (clientData.AchievementsList.Count > 0)
{
AchievementsInfo[] AchievementsArray = clientData.AchievementsList.ToArray();
data.AchievementsList.Clear();
data.AchievementsList.AddRange(AchievementsArray);
}
if (clientData.CardsList.Count > 0)
{
CardInfo[] CardsArray = clientData.CardsList.ToArray();
data.CardsList.Clear();
data.CardsList.AddRange(CardsArray);
}
YandexGame.savesData.Breads = data.Breads;
YandexGame.savesData.TotalBreads = data.TotalBreads;
YandexGame.savesData.ProfitPerHour = data.ProfitPerHour;
YandexGame.savesData.ClicksAmount = data.ClicksAmount;
YandexGame.savesData.FirstPurchase = data.FirstPurchase;
YandexGame.savesData.UnknowCardBought = data.UnknowCardBought;
YandexGame.savesData.AplicationWasClosed = data.AplicationWasClosed;
YandexGame.savesData.LastSession = data.LastSession;
YandexGame.savesData.TimeInGame = data.TimeInGame;
YandexGame.savesData.CardsList = data.CardsList;
YandexGame.savesData.AchievementsList = data.AchievementsList;
Debug.Log("ПРОЦЕСС СОХРАНЕНИЯ");
foreach (var card in YandexGame.savesData.CardsList)
{
Debug.Log("RegularCardsList[i].name = " + card.name);
Debug.Log("RegularCardsList[i].alreadyBought = " + card.alreadyBought);
Debug.Log("RegularCardsList[i].available = " + card.available);
Debug.Log("RegularCardsList[i].level = " + card.level);
Debug.Log("RegularCardsList[i].base_price = " + card.base_price);
Debug.Log("RegularCardsList[i].base_profit = " + card.base_profit);
}
YandexGame.SaveProgress();
// Сериализуем и записываем обратно в файл
//string datajson = JsonConvert.SerializeObject(data);
//File.WriteAllText("Assets/Scripts/Saves/datajson.json", datajson);
}
public static DataStructure LoadData()
{
//string json = File.ReadAllText("Assets/Scripts/Saves/datajson.json");
//DataStructure data = JsonConvert.DeserializeObject<DataStructure>(json);
DataStructure data = new DataStructure();
data.Breads = YandexGame.savesData.Breads;
data.TotalBreads = YandexGame.savesData.TotalBreads;
data.ProfitPerHour = YandexGame.savesData.ProfitPerHour;
data.ClicksAmount = YandexGame.savesData.ClicksAmount;
data.FirstPurchase = YandexGame.savesData.FirstPurchase;
data.UnknowCardBought = YandexGame.savesData.UnknowCardBought;
data.AplicationWasClosed = YandexGame.savesData.AplicationWasClosed;
data.LastSession = YandexGame.savesData.LastSession;
data.TimeInGame = YandexGame.savesData.TimeInGame;
CardInfo[] CardsArray = YandexGame.savesData.CardsList.ToArray();
data.CardsList.Clear();
data.CardsList.AddRange(CardsArray);
AchievementsInfo[] AchievementsArray = YandexGame.savesData.AchievementsList.ToArray();
data.AchievementsList.Clear();
data.AchievementsList.AddRange(AchievementsArray);
Debug.Log("ЗАГРУЗКА СОХРАНЕНИЯ");
Debug.Log(" data.Breads = " + data.Breads);
Debug.Log(" data.TotalBreads = " + data.TotalBreads);
Debug.Log(" data.ProfitPerHour = " + data.ProfitPerHour);
Debug.Log(" data.ClicksAmount = " + data.ClicksAmount);
Debug.Log(" data.FirstPurchase = " + data.FirstPurchase);
Debug.Log(" data.UnknowCardBought = " + data.UnknowCardBought);
Debug.Log(" data.AplicationWasClosed = " + data.AplicationWasClosed);
Debug.Log(" data.LastSession = " + data.LastSession);
Debug.Log(" data.TimeInGame = " + data.TimeInGame);
foreach (var card in data.CardsList)
{
Debug.Log("RegularCardsList[i].name = " + card.name);
Debug.Log("RegularCardsList[i].alreadyBought = " + card.alreadyBought);
Debug.Log("RegularCardsList[i].available = " + card.available);
Debug.Log("RegularCardsList[i].level = " + card.level);
Debug.Log("RegularCardsList[i].base_price = " + card.base_price);
Debug.Log("RegularCardsList[i].base_profit = " + card.base_profit);
}
return data;
}
}
Файл с карточками (где и возникает проблема)
DataStructure clientData;
public double breads, total_breads;
public double profitPerHour;
string PathCardLevel_Value, PathCardProfit_Value, PathCardPrice_Value, PathCardFutureProfit_Value;
Transform CardLevel_Value, CardProfit_Value, CardPrice_Value, CardFutureProfit_Value;
TMP_Text TCardLevel_Value, TCardProfit_Value, TCardPrice_Value, TCardFutureProfit_Value;
NumbersReduction NumRed;
public CardInfo[] RegularCardsList, SpecialCardsList, LegendCardsList;
public TMP_Text breadsOutput;
void Start()
{
GetLoad();
NumRed = new NumbersReduction();
StartCoroutine(AutoFarm());
}
void OnDisable()
{
SaveGameData();
}
public void GetLoad()
{
clientData = SavesJSON.LoadData();
breads = (double)clientData.Breads;
total_breads = (double)clientData.TotalBreads;
profitPerHour = clientData.ProfitPerHour;
LoadCardsData();
}
public void SaveGameData()
{
//var regularCardsList = new List<CardInfo>(RegularCardsList);
//var specialCardsList = new List<CardInfo>(SpecialCardsList);
//var legendCardsList = new List<CardInfo>(LegendCardsList);
clientData.CardsList.Clear();
clientData.CardsList.AddRange(RegularCardsList);
clientData.CardsList.AddRange(SpecialCardsList);
clientData.CardsList.AddRange(LegendCardsList);
Debug.Log("clientData.CardsList.Count = " + clientData.CardsList.Count);
foreach (var card in clientData.CardsList)
{
Debug.Log("card.name = " + card.name);
}
clientData.Breads = (int)breads;
clientData.TotalBreads = (int)total_breads;
// Создаем JSON данные
SavesJSON.CreateData(clientData);
}
void LoadCardsData()
{
for (int i = 0; i < clientData.CardsList.Count; i++)
{
Debug.Log("МАГАЗИН");
Debug.Log("clientData.CardsList.Count = " + clientData.CardsList.Count);
if (RegularCardsList.Length >= i && clientData.CardsList[i].category == "Regular")
{
RegularCardsList[i].alreadyBought = clientData.CardsList[i].alreadyBought;
RegularCardsList[i].available = clientData.CardsList[i].available;
RegularCardsList[i].level = clientData.CardsList[i].level;
RegularCardsList[i].base_price = clientData.CardsList[i].base_price;
RegularCardsList[i].base_profit = clientData.CardsList[i].base_profit;
Debug.Log("RegularCardsList[i].name = " + RegularCardsList[i].name);
Debug.Log("RegularCardsList[i].alreadyBought = " + RegularCardsList[i].alreadyBought);
Debug.Log("RegularCardsList[i].available = " + RegularCardsList[i].available);
Debug.Log("RegularCardsList[i].level = " + RegularCardsList[i].level);
Debug.Log("RegularCardsList[i].base_price = " + RegularCardsList[i].base_price);
Debug.Log("RegularCardsList[i].base_profit = " + RegularCardsList[i].base_profit);
}
if (SpecialCardsList.Length >= i && clientData.CardsList[i].category == "Special")
{
SpecialCardsList[i].alreadyBought = clientData.CardsList[i].alreadyBought;
SpecialCardsList[i].available = clientData.CardsList[i].available;
SpecialCardsList[i].level = clientData.CardsList[i].level;
SpecialCardsList[i].base_price = clientData.CardsList[i].base_price;
SpecialCardsList[i].base_profit = clientData.CardsList[i].base_profit;
}
if (LegendCardsList.Length >= i && clientData.CardsList[i].category == "Legend")
{
LegendCardsList[i].alreadyBought = clientData.CardsList[i].alreadyBought;
LegendCardsList[i].available = clientData.CardsList[i].available;
LegendCardsList[i].level = clientData.CardsList[i].level;
LegendCardsList[i].base_price = clientData.CardsList[i].base_price;
LegendCardsList[i].base_profit = clientData.CardsList[i].base_profit;
}
}
}
SavesYG:
using System.Collections.Generic;
namespace YG
{
[System.Serializable]
public class SavesYG
{
// "Технические сохранения" для работы плагина (Не удалять)
public int idSave;
public bool isFirstSession = true;
public string language = "ru";
public bool promptDone;
// Тестовые сохранения для демо сцены
// Можно удалить этот код, но тогда удалите и демо (папка Example)
// Ваши сохранения
public int Breads;
public int TotalBreads;
public double ProfitPerHour;
public int ClicksAmount;
public bool FirstPurchase;
public bool UnknowCardBought;
public bool AplicationWasClosed;
public string LastSession;
public double TimeInGame;
public List<CardInfo> CardsList;
public List<AchievementsInfo> AchievementsList;
// Поля (сохранения) можно удалять и создавать новые. При обновлении игры сохранения ломаться не должны
// Вы можете выполнить какие то действия при загрузке сохранений
public SavesYG()
{
// Допустим, задать значения по умолчанию для отдельных элементов массива
//openLevels[1] = true;
}
}
}