rabidus-test/Assets/Scripts/SaveLoadController.cs

73 lines
1.9 KiB
C#
Raw Permalink Normal View History

2023-08-22 17:02:25 +03:00
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
public class SaveLoadController : MonoBehaviour
{
public static SaveLoadController Instance;
private const string DIR_PATH = "/game_save/players/";
private const string FILE_PATH = "players.txt";
private void Awake()
{
if(Instance == null)
{
Instance = this;
}
else if (Instance != this)
{
Destroy(this);
}
DontDestroyOnLoad(this);
}
public void Save<T>(T so) where T: ScriptableObject
{
string fullDirPath = Application.persistentDataPath + DIR_PATH;
string fullFilePath = Application.persistentDataPath + DIR_PATH + FILE_PATH;
if (!Directory.Exists(fullDirPath))
{
Directory.CreateDirectory(fullDirPath);
}
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = File.Create(fullFilePath);
var json = JsonUtility.ToJson(so);
bf.Serialize(fs, json);
fs.Close();
}
public void Load<T>(ref T so) where T: ScriptableObject
{
string fullDirPath = Application.persistentDataPath + DIR_PATH;
string fullFilePath = Application.persistentDataPath + DIR_PATH + FILE_PATH;
Debug.Log(fullFilePath);
Debug.Log(fullDirPath);
if (!Directory.Exists(fullDirPath))
{
Directory.CreateDirectory(fullDirPath);
}
BinaryFormatter bf = new BinaryFormatter();
if (File.Exists(fullFilePath))
{
FileStream fs = File.Open(fullFilePath, FileMode.Open);
so = ScriptableObject.CreateInstance<T>();
JsonUtility.FromJsonOverwrite((string)bf.Deserialize(fs), so);
fs.Close();
}
else
{
so = ScriptableObject.CreateInstance<T>();
}
}
}