Skip to content

Instantly share code, notes, and snippets.

@gamemachine
Created September 12, 2015 23:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gamemachine/151382558a1f5dd0ec5d to your computer and use it in GitHub Desktop.
Save gamemachine/151382558a1f5dd0ec5d to your computer and use it in GitHub Desktop.
Scriptablable object as protobuf message container
using UnityEngine;
using io.gamemachine.messages;
namespace GameMachine {
namespace ItemManagement {
[CreateAssetMenu(menuName =@"ItemCatalog")]
public class ItemCatalog : ScriptableProtobuf<PlayerItems> {
}
}
}
message PlayerItem {
...
}
message PlayerItems {
repeated PlayerItem playerItems = 1;
}
using UnityEngine;
using System.IO;
using ProtoBuf;
using System;
namespace GameMachine {
public class ScriptableProtobuf<T> : ScriptableObject where T :IExtensible {
public static string dataDirectory = System.IO.Path.GetFullPath(Application.dataPath + "/protobuf_data");
public static string fileExtension = ".pb";
public string id;
private T data;
private bool loaded = false;
public T GetData() {
if (!loaded) {
Load();
}
return data;
}
public void Save() {
MemoryStream stream = new MemoryStream();
Serializer.Serialize(stream, data);
System.IO.File.WriteAllBytes(DataFilePath(), stream.ToArray());
loaded = false;
}
public T Clone(T data) {
MemoryStream stream = new MemoryStream();
Serializer.Serialize(stream, data);
stream = new MemoryStream(stream.ToArray());
return Serializer.Deserialize<T>(stream);
}
public void Import(byte[] bytes) {
System.IO.File.WriteAllBytes(DataFilePath(), bytes);
loaded = false;
}
private void EnsurePath() {
if (!System.IO.Directory.Exists(dataDirectory)) {
System.IO.Directory.CreateDirectory(dataDirectory);
}
}
private string DataFilePath() {
if (string.IsNullOrEmpty(id)) {
id = Guid.NewGuid().ToString();
}
return dataDirectory + "/" + this.GetType().Name+"_"+id + fileExtension;
}
private bool DataFileExists() {
return (File.Exists(DataFilePath()));
}
private void Load() {
if (!loaded) {
EnsurePath();
if (!DataFileExists()) {
data = Activator.CreateInstance<T>();
} else {
byte[] bytes = System.IO.File.ReadAllBytes(DataFilePath());
MemoryStream stream = new MemoryStream(bytes);
data = Serializer.Deserialize<T>(stream);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment