Manage save games in Unity without pain using NDatabase

public class PlayerData {
public float[] PositionData;
public int Score;
public int Lives;
public List Inventory = new List ();


///
/// Gets or sets the position array
///
/// The position.
public Vector3 Position {
get {
if (PositionData == null) {
return Vector3.zero;
}
Vector3 result;
for (int i = 0; i < 3; i++) {
result [i] = PositionData [i];
}
return result;
}
set{
PositionData = new float[3]{ value.x, value.y, value.z };
}
}
}
public class Player : MonoBehaviour
{
private string _savegamePath;
private IOdb _dataStorage;
public PlayerData Data { get; private set; }

private void Awake ()
{
_savegamePath = Application.persistentDataPath + "/savegame";
LoadFirstSavegame ();
}

private void LoadFirstSavegame ()
{
_dataStorage = OdbFactory.Open (_savegamePath);

Data = _dataStorage.QueryAndExecute ().GetFirst ();
if (Data == null) {
Data = new PlayerData ();
} else {
transform.position = Data.Position;
}
}

private void OnApplicationPause (bool pause)
{
if (pause) {
SavePlayerData ();
} else {
if (_dataStorage == null || _dataStorage.IsClosed ()) {
LoadFirstSavegame ();
}
}
}

private void OnApplicationQuit ()
{
if (_dataStorage != null) {
SavePlayerData ();
_dataStorage.Dispose ();
}
}

private void SavePlayerData ()
{
Data.Position = transform.position;
_dataStorage.Store (Data);
_dataStorage.Commit ();
}
}
IOdb _dataStorage = OdbFactory.Open (savegamePath);
_dataStorage.Store (theObject);
_dataStorage.Commit();
_dataStorage.Store (Data);
var result = _dataStorage.QueryAndExecute ();
Data = result.GetFirst();

 by the author.

--

--

Technology visionary working at Accenture’s Extended Reality Studios Zurich & Nature Lover. The views expressed are my personal views, not those of my employer.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store