Skip to content

Instantly share code, notes, and snippets.

@oliverbooth
Last active April 27, 2021 13:30
Show Gist options
  • Save oliverbooth/030fbe6a9b934a738c5e191682a2e0ab to your computer and use it in GitHub Desktop.
Save oliverbooth/030fbe6a9b934a738c5e191682a2e0ab to your computer and use it in GitHub Desktop.
Complete PlayerBehaviour & SaveData example
using System.IO;
using ProtoBuf;
using ProtoBuf.Meta;
using UnityEngine;
public class PlayerBehaviour : MonoBehaviour
{
private string _saveFile;
[field: SerializeField]
public int Score { get; set; } = 0;
[field: SerializeField]
public float Health { get; set; } = 100;
static PlayerBehaviour()
{
var model = RuntimeTypeModel.Default;
model.Add<Vector3Surrogate>();
model.Add<Vector3>(false).SetSurrogate(typeof(Vector3Surrogate));
}
private void Awake()
{
_saveFile = Path.Combine(Application.persistentDataPath, "save001.dat");
LoadGame();
}
private void OnApplicationQuit()
{
SaveGame();
}
private void LoadGame()
{
if (!File.Exists(_saveFile))
return;
using var file = File.OpenRead(_saveFile);
var data = Serializer.Deserialize<SaveData>(file);
Score = data.Score;
Health = data.Health;
transform.position = data.Position;
}
private void SaveGame()
{
using var file = File.Create(_saveFile);
var data = new SaveData
{
Score = this.Score,
Health = this.Health,
Position = transform.position
};
Serializer.Serialize(file, data);
}
}
using ProtoBuf;
using UnityEngine;
[ProtoContract]
public class SaveData
{
[ProtoMember(1)]
public int Score { get; set; }
[ProtoMember(2)]
public float Health { get; set; }
[ProtoMember(3)]
public Vector3 Position { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment