之前用的protobuf, 但是记得之前的demo使用的是google.protobuf,所以就又弄了一下。
先去git上拉取,git的readme上说 直接build一下c#的sln。然而我查了一上午资料也不能生成.exe。
索性直接下载了win32.tar(这个在 git上有,每个版本的最下面)。他可以直接运行c#的.proto.
感觉剩下的操作,官网上说的很清楚了,就不记录了。
之后是书写上的内容:
这里主要记录了proto的list方法,以及map[key,value]方法, 这里以map[string ,list ]为例
proto:
syntax = "proto3"; message ComplexObject { int32 id = 1;// 默认值,表示成员只有0个或者1个 string name = 2;// string email = 3;// repeated Result sons = 4; // repeated 列表 Gender gender = 5; // Enum值 map<string, MapVaule> map = 6; // 定义Map对象 map<string, list> mapList=7;//定义string 连着一串list } message list{ repeated Result ele=1; } enum Gender { MAN = 0; WOMAN = 1; } // 定义一个新的对象 message Result { string url = 1; string title = 2; repeated string snippets = 3; }
之后是C#对应的使用例子
using UnityEngine; using Google.Protobuf; namespace MainClient { public class testProto : MonoBehaviour { void Start() { ComplexObject test = new ComplexObject(); test.Id=200;//普通变量赋值 //list变量赋值 //先初始化类型 Result res = new Result(); res.Title = "a"; //放入repeated test.Sons.Add(res); Result res2 = new Result(); res2.Title = "b"; test.Sons.Add(res2); foreach(var i in test.Sons) { Debug.Log(i.Title); } ///map [string , list] 使用方法 ///这个list 在proto中必须是个message单独的,不能和map 同级,具体看proto ///先初始化list list testList = new list(); Result newResult = new Result(); newResult.Title = "c"; testList.Ele.Add(newResult); Result newResult2 = new Result(); newResult2.Title = "d"; testList.Ele.Add(newResult2); list testList2 = new list(); Result newResult3 = new Result(); newResult3.Title = "e"; testList2.Ele.Add(newResult2); Result newResult4 = new Result(); newResult4.Title = "f"; testList2.Ele.Add(newResult2); //放入map test.MapList["c"] = testList; test.MapList["d"] = testList2; //得到对应的map[key] 的value list ans = new list(); Debug.Log(test.MapList.TryGetValue("c",out ans)); foreach (var i in ans.Ele) { Debug.Log("map key = c: value="+ i.Title); } } } }