Scriptum/Assets/Scripts/REFACTORING/Application/Panel/Chest/SaveChestManager.cs
2022-11-28 00:52:47 +01:00

99 lines
2.8 KiB
C#

using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
public class SaveChestManager : SaveModelSystem<ChestPrefabAsset>
{
public override bool SaveModelItem(ChestPrefabAsset model)
{
return base.SaveModelItem(model);
}
public override bool SaveModelList(List<ChestPrefabAsset> list)
{
BinaryFormatter formatter = new BinaryFormatter();
Debug.Log("Saved Chest at " + Path);
if (!Directory.Exists(Path)) Directory.CreateDirectory(Path);
/* Main logic of conversion data format */
var data = ConvertObjectsListToListOfDataModels(list);
FileStream stream = new FileStream(
Path + GetFileName(ObjectListName),
FileMode.Create
);
formatter.Serialize(stream, data);
stream.Close();
return true;
}
public override ChestPrefabAsset LoadModelItem()
{
return base.LoadModelItem();
}
public override List<ChestPrefabAsset> LoadModelList()
{
string path = Path + GetFileName(ObjectListName);
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
List<ChestPrefabAssetData> questsList = formatter.Deserialize(stream) as List<ChestPrefabAssetData>;
stream.Close();
return ConvertListOfDataModelsToListOfObject(questsList);
}
else
{
Debug.Log("Save file not found in " + path);
}
return new List<ChestPrefabAsset>();
}
// Support function
// 1. From model to data format
public static ChestPrefabAssetData ConvertObjectToDataModel(ChestPrefabAsset model)
{
return new ChestPrefabAssetData(model);
}
public static List<ChestPrefabAssetData> ConvertObjectsListToListOfDataModels(List<ChestPrefabAsset> modelsList)
{
List<ChestPrefabAssetData> convertedList = new List<ChestPrefabAssetData>();
foreach(ChestPrefabAsset model in modelsList)
{
convertedList.Add(ConvertObjectToDataModel(model));
}
return convertedList;
}
// 2. From data to model format
public static ChestPrefabAsset ConvertDataModelToObject(ChestPrefabAssetData dataModel)
{
return (ChestPrefabAsset)dataModel.MapDataToPrefabAssetModel();
}
public static List<ChestPrefabAsset> ConvertListOfDataModelsToListOfObject(List<ChestPrefabAssetData> dataModelsList)
{
List<ChestPrefabAsset> convertedList = new List<ChestPrefabAsset>();
foreach (ChestPrefabAssetData dataModel in dataModelsList)
{
convertedList.Add(ConvertDataModelToObject(dataModel));
}
return convertedList;
}
}