109 lines
3.1 KiB
C#
109 lines
3.1 KiB
C#
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 void Awake()
|
|
{
|
|
//transform.parent = null;
|
|
|
|
if (Instance == null)
|
|
{
|
|
Instance = this;
|
|
//DontDestroyOnLoad(gameObject);
|
|
}
|
|
else if (Instance != this)
|
|
{
|
|
Destroy(gameObject);
|
|
}
|
|
}
|
|
|
|
public bool Save<T>(T so, string filename) where T : ScriptableObject
|
|
{
|
|
string fullDirPath = Application.persistentDataPath + DIR_PATH;
|
|
string fullFilePath = Application.persistentDataPath + DIR_PATH + $"{filename}.txt";
|
|
|
|
Debug.Log($"SAVE:{fullFilePath}");
|
|
if (!Directory.Exists(fullDirPath))
|
|
{
|
|
Directory.CreateDirectory(fullDirPath);
|
|
}
|
|
|
|
using (FileStream fs = File.Create(fullFilePath))
|
|
{
|
|
var json = JsonUtility.ToJson(so);
|
|
byte[] info = new System.Text.UTF8Encoding(true).GetBytes(json);
|
|
fs.Write(info, 0, info.Length);
|
|
fs.Close();
|
|
}
|
|
|
|
Debug.Log($"SAVE:SUCCESS");
|
|
return true;
|
|
}
|
|
|
|
public T Load<T>(ref T so, string filename) where T : ScriptableObject
|
|
{
|
|
string fullDirPath = Application.persistentDataPath + DIR_PATH;
|
|
string fullFilePath = Application.persistentDataPath + DIR_PATH + $"{filename}.txt";
|
|
|
|
Debug.Log($"LOAD:{fullFilePath}");
|
|
|
|
if (!Directory.Exists(fullDirPath))
|
|
{
|
|
Directory.CreateDirectory(fullDirPath);
|
|
}
|
|
|
|
if (File.Exists(fullFilePath))
|
|
{
|
|
using (FileStream fs = File.Open(fullFilePath, FileMode.Open))
|
|
{
|
|
using (StreamReader reader = new StreamReader(fs))
|
|
{
|
|
var file = reader.ReadToEnd();
|
|
so = ScriptableObject.CreateInstance<T>();
|
|
JsonUtility.FromJsonOverwrite(file, so);
|
|
fs.Close();
|
|
}
|
|
}
|
|
}
|
|
|
|
Debug.Log($"LOAD:SUCCESS");
|
|
return default;
|
|
}
|
|
|
|
public bool LoadOld<T>(ref T so, string filename) where T : ScriptableObject
|
|
{
|
|
string fullDirPath = Application.persistentDataPath + DIR_PATH;
|
|
string fullFilePath = Application.persistentDataPath + DIR_PATH + $"{filename}.txt";
|
|
|
|
Debug.Log($"LOAD:{fullFilePath}");
|
|
|
|
if (!Directory.Exists(fullDirPath))
|
|
{
|
|
Directory.CreateDirectory(fullDirPath);
|
|
}
|
|
|
|
BinaryFormatter bf = new BinaryFormatter();
|
|
|
|
if (File.Exists(fullFilePath))
|
|
{
|
|
using (FileStream fs = File.Open(fullFilePath, FileMode.Open))
|
|
{
|
|
so = ScriptableObject.CreateInstance<T>();
|
|
JsonUtility.FromJsonOverwrite((string)bf.Deserialize(fs), so);
|
|
fs.Close();
|
|
}
|
|
}
|
|
|
|
Debug.Log($"LOAD:SUCCESS");
|
|
return true;
|
|
}
|
|
}
|