前言
在Unity游戏开发中,高效、快速、安全地读取配置数据是一项重要需求。本文介绍一种完整的解决方案——使用Protobuf二进制格式(Pb2)存储和读取游戏数据,并详细分享实现全流程的Unity工具。
一、技术流程概览
实现Unity读取Pb2二进制数据的流程如下:
- Excel设计数据表
- Excel转Proto文件
- Proto文件转C#类
- Excel数据序列化为Pb2二进制文件
- Unity中加载Pb2数据文件
二、具体实现步骤
1. Excel设计数据表
数据表应遵循特定的格式规范:
- 第一行:字段注释
- 第二行:字段名(英文变量名)
- 第三行:字段数据类型(例如int32、string)
- 第四行及以下:数据内容

2. Excel转Proto文件
使用自定义编辑器工具自动将Excel表转换为.proto文件。
关键代码:ProtoGenerator.cs
private void GenerateProtoFile()
{
FileInfo fileInfo = new FileInfo(excelFilePath);
if (!fileInfo.Exists)
{
Debug.LogError("Excel 文件不存在: " + excelFilePath);
return;
}
// 确保输出目录存在
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
// 定义 .proto 文件头部信息
string protoContent = "syntax = \"proto3\";\n";
protoContent += "package GameDataProto;\n\n";
using (ExcelPackage package = new ExcelPackage(fileInfo))
{
// 遍历所有工作表,每个工作表生成一个 message
foreach (ExcelWorksheet worksheet in package.Workbook.Worksheets)
{
string messageName = worksheet.Name;
protoContent += $"message {messageName} {
{\n";
// 假定第一行为注释,第二行为变量名,第三行为类型
int colCount = worksheet.Dimension.Columns;
int fieldIndex = 1;
for (int col = 1; col <= colCount; col++)
{
object commentObj = worksheet.Cells[1, col].Value;
object variableNameObj = worksheet.Cells[2, col].Value;
object typeObj = worksheet.Cells[3, col].Value;
if (variableNameObj == null || typeObj == null)
continue;
string comment = commentObj != null ? commentObj.ToString().Trim() : "";
string variableName = variableNameObj.ToString().Trim();
string type = typeObj.ToString().Trim();
if (!string.IsNullOrEmpty(comment))
{
protoContent += $" // {comment}\n";
}
protoContent += $" {type} {variableName} = {fieldIndex};\n";
fieldIndex++;
}
protoContent += "}\n\n";
}
}
string protoFilePath = Path.Combine(outputFolder, "GameDataProto.proto");

最低0.47元/天 解锁文章
2350

被折叠的 条评论
为什么被折叠?



