This save system can be used to store any amount of data in a binary file on the user's device for later use. This could be as simple as a highscore table or as complex as tracking quest progress in an RPG.
// SaveManager.cs
using System.IO;
using UnityEngine;
namespace FallingSloth.SaveManager
{
public class SaveManager<T> where T: SaveData, new()
{
BinaryFormatter formatter;
protected string dataPath
{
get
{
return Application.persistentDataPath + "/" + filename;
}
}
protected string filename = "save.sav";
public SaveManager(string filename)
{
this.filename = filename;
}
T _data;
protected T data
{
get
{
if (_data == null) LoadData();
return _data;
}
set
{
_data = value;
}
}
private void LoadData()
{
if (File.Exists(dataPath))
{
using (FileStream stream = new FileStream(dataPath, FileMode.Open))
{
try
{
DeserialiseData(stream);
}
catch
{
data = new T();
}
}
}
else
{
data = new T();
}
}
public void SaveData()
{
FileMode mode = (File.Exists(dataPath)) ? FileMode.Open : FileMode.Create;
using (FileStream stream = new FileStream(dataPath, mode))
{
SerialiseData(stream);
}
}
private void SerialiseData(FileStream stream)
{
if (formatter == null) formatter = new BinaryFormatter();
formatter.Serialize(stream, data);
}
private void DeserialiseData(FileStream stream)
{
if (formatter == null) formatter = new BinaryFormatter();
data = (T)formatter.Deserialize(stream);
}
}
}
// SaveData.cs
namespace FallingSloth.SaveManager
{
[Serializable]
public abstract class SaveData
{
}
}
sbobet | Bet on Sport Online | Sbobet Casino
ReplyDeleteJoin happyluke Sbobet Casino and enjoy over 200 sbobet ทางเข้า betting markets to choose from. Enjoy our range 코인카지노 of casino games, live casino and sportsbook