Skip to content

Instantly share code, notes, and snippets.

@koshelevpavel
Created August 30, 2019 16:55
Show Gist options
  • Select an option

  • Save koshelevpavel/8e2d62053fc79b2bf9e2105d18b056bc to your computer and use it in GitHub Desktop.

Select an option

Save koshelevpavel/8e2d62053fc79b2bf9e2105d18b056bc to your computer and use it in GitHub Desktop.
protobuf-net and unity example
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using ProtoBuf;
using ProtoBuf.Meta;
using UnityEditor;
using UnityEditor.Compilation;
using UnityEngine;
using Assembly = UnityEditor.Compilation.Assembly;
public class ProtobufSerializerCheck : MonoBehaviour
{
[ProtoContract]
public class MyProtoClass
{
[ProtoMember(1)]
public Vector2 v2;
[ProtoMember(2)]
public Vector3 v3;
[ProtoMember(3)]
public int i;
}
private void Awake()
{
MyProtoClass myProtoClass = new MyProtoClass();
myProtoClass.v2 = new Vector2(2, 2);
myProtoClass.v3 = new Vector3(2, 2, 0);
myProtoClass.i =10;
TypeModel model = (TypeModel)Activator.CreateInstance(Type.GetType("MyProtoModel, MyProtoModel"));//new MyProtoModel();
using (Stream stream = new MemoryStream(1024))
{
model.Serialize(stream, myProtoClass);
stream.Position = 0L;
MyProtoClass desClass = (MyProtoClass) model.Deserialize(stream, null, typeof(MyProtoClass));
Debug.Log(desClass.v2);
Debug.Log(desClass.v3);
Debug.Log(desClass.i);
}
}
#if UNITY_EDITOR
[MenuItem("Protobuf/Build model")]
private static void BuildMyProtoModel()
{
RuntimeTypeModel typeModel = GetModel();
typeModel.Compile("MyProtoModel", "MyProtoModel.dll");
if (!Directory.Exists("Assets/Plugins"))
{
Directory.CreateDirectory("Assets/Plugins");
}
File.Copy("MyProtoModel.dll", "Assets/Plugins/MyProtoModel.dll");
AssetDatabase.Refresh();
}
[MenuItem("Protobuf/Create proto file")]
private static void CreateProtoFile()
{
RuntimeTypeModel typeModel = GetModel();
using (FileStream stream = File.Open("model.proto", FileMode.Create))
{
byte[] protoBytes = Encoding.UTF8.GetBytes(typeModel.GetSchema(null));
stream.Write(protoBytes, 0, protoBytes.Length);
}
}
private static RuntimeTypeModel GetModel()
{
RuntimeTypeModel typeModel = TypeModel.Create();
foreach (var t in GetTypes(CompilationPipeline.GetAssemblies()))
{
var contract = t.GetCustomAttributes(typeof(ProtoContractAttribute), false);
if (contract.Length > 0)
{
typeModel.Add(t, true);
//add unity types
typeModel.Add(typeof(Vector2), false).Add("x", "y");
typeModel.Add(typeof(Vector3), false).Add("x", "y", "z");
}
}
return typeModel;
}
private static IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
{
foreach (Assembly assembly in assemblies)
{
foreach (Type type in AppDomain.CurrentDomain.Load(assembly.name).GetTypes())
{
yield return type;
}
}
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment