一. 下载与安装
这里下载
Google Protobuff下载

1. 源码用来编译CSharp 相关配置
2. win64 用于编译 proto 文件
二. 编译
1. 使用VS 打开

2. 点击最上面菜单栏 工具>NuGet 包管理器>管理解决方案的NuGet 管理包

版本一定要选择咱们一开始下载的对应版本否则不兼容!这里选择3.25.3。然后点击安装.
3.编译项目

拷贝文件

unity 目录

三.proto 文件
新建txt文本取名Person.proto,切记后缀.txt改为.proto
 输入一下代码
syntax="proto3";//指定了正在使用proto3语法,如果没指定编译器默认使用proto2语法
package TestGoogleProtoBuff;//等于C#中命名空间
message personInfo
{
	string name=1;
	int32 age=2;
	int64 money=3;
	message PhoneNumber{
		string number=1;
		PhoneType type=2;
	}
	repeated PhoneNumber phone=5;
}
enum PhoneType{
	HOME=0;
	WORK=1;
	MOBILE=2;
}
 
编译
然后在这个文件夹中创建ExProtProto.bat,输入一下命令并保存。
双击ExProtProto.bat,我们发现生成了Person.cs文件
四.Unity中的使用
然后我们打开unity,新建文件夹Proto,将刚刚生成好的Person.cs代码放在Proto文件夹中。
我们在unity中新建ProtoBufffer.cs脚本
using Google.Protobuf;
public class ProtoBufffer
{
    public static byte[] Serialize(IMessage message)
    {
        return message.ToByteArray();
    }
    public static T DeSerialize<T>(byte[] packet)where T:IMessage, new()
    {
        IMessage message = new T();
        try
        {
            return (T)message.Descriptor.Parser.ParseFrom(packet);
        }
        catch (System.Exception e)
        {
            throw;
        }
    }
}
 
在创建一个Test.cs脚本来测试该功能,将该脚本拖到主摄像机上
using TestGoogleProtoBuff;
using UnityEngine;
public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        personInfo info = new personInfo();
        info.Name = "ys";
        info.Age = 50;
        info.Money = 9999;
        info.Phone.Add(new personInfo.Types.PhoneNumber { Number = "12123",Type=PhoneType.Home});
        byte[] msg = ProtoBufffer.Serialize(info);
        Debug.Log(msg.Length);
        personInfo deinfo  = ProtoBufffer.DeSerialize<personInfo>(msg);
        Debug.Log("姓名:"+deinfo.Name);
        Debug.Log("年龄:"+deinfo.Age);
        Debug.Log("资产:" + deinfo.Money);
        Debug.Log($"{deinfo.Phone[0].Type}的电话号:{deinfo.Phone[0].Number}");
    }
}
 
                












![[AutoSar]BSW_Com03 DBC详解 (二)](https://img-blog.csdnimg.cn/direct/da7d3b4ec66b45e1b7416378b0ca765a.png)





