Scriptum/Assets/Scripts/REFACTORING/Application/Panel/Chest/SaveChestManager.cs

99 lines
2.8 KiB
C#
Raw Normal View History

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
private ChestPrefabAssetData ConvertObjectToDataModel(ChestPrefabAsset model)
{
return new ChestPrefabAssetData(model);
}
private 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
private ChestPrefabAsset ConvertDataModelToObject(ChestPrefabAssetData dataModel)
{
return (ChestPrefabAsset)dataModel.MapDataToPrefabAssetModel();
}
private List<ChestPrefabAsset> ConvertListOfDataModelsToListOfObject(List<ChestPrefabAssetData> dataModelsList)
{
List<ChestPrefabAsset> convertedList = new List<ChestPrefabAsset>();
foreach (ChestPrefabAssetData dataModel in dataModelsList)
{
convertedList.Add(ConvertDataModelToObject(dataModel));
}
return convertedList;
}
}