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 GetTypes(IEnumerable assemblies) { foreach (Assembly assembly in assemblies) { foreach (Type type in AppDomain.CurrentDomain.Load(assembly.name).GetTypes()) { yield return type; } } } #endif }