>版權(quán)聲明:本文為Jumbo原創(chuàng)文章,采用[知識(shí)共享 署名-非商業(yè)性使用-禁止演繹 4.0 國(guó)際 許可協(xié)議],轉(zhuǎn)載前請(qǐng)保證理解此協(xié)議
原文出處:http://www.reibang.com/p/747c63d5d56b
將Excel表格數(shù)據(jù)轉(zhuǎn)成Protobuf V3【Unity】
作者:Jumbo @2015/12/30
工作原理流程:
1汛聚、xls2protobuf_v3.py 將表格數(shù)據(jù)轉(zhuǎn)成:*.proto *.bin *.txt等
2涛菠、protoc.exe 通過(guò)讀取*.proto生成*.cs腳本解析類(lèi)
3残黑、Unity通過(guò)protobuf-V3.0\csharp_unity\Google.Protobuf插件讀取*.bin文件
準(zhǔn)備工作:
1寝优、安裝Python2.7,配置系統(tǒng)環(huán)境變量苫亦,如下圖:
2毛肋、切換到目錄setuptools-18.7奕锌,執(zhí)行 python setup.py install
3、切換到目錄xlrd-0.9.4村生,執(zhí)行 python setup.py install
4、切換到目錄protobuf-V3.0\python饼丘,執(zhí)行 python setup.py install
開(kāi)始轉(zhuǎn)換:
1趁桃、轉(zhuǎn)換工具目錄結(jié)構(gòu):
-ConvertTools
-xls表格數(shù)據(jù)
-xls2proto通過(guò)表格數(shù)據(jù)生成*.proto(描述文件) *.bin(二進(jìn)制) *.txt(明文)等
-proto2cs生成的*.cs文件
-ConvertList.txt批處理數(shù)據(jù)轉(zhuǎn)換列表,配合ResConvertAll.bat
-ResConvertAll.bat 執(zhí)行批處理轉(zhuǎn)換所有數(shù)據(jù)肄鸽,讀取ConverList.txt
-ResConvert.bat 單個(gè)表格數(shù)據(jù)處理命令格式:ResConvert [表格名] [xls文件名]
-xls2protobuf_v3.py 表格數(shù)據(jù)轉(zhuǎn)換工具卫病,支持proto3最新格式
2、數(shù)據(jù)表格制作: 參考xls2protobuf_v3.py定義描述
3典徘、protoc.exe相關(guān)命令參數(shù) : protoc --help查看 需要配置環(huán)境變量蟀苛,在Path后面加上;{protobuf-V3.0\src\protoc.exe 路徑目錄}
Unity使用:
1、protobuf支持Unity的CSharp庫(kù):將protobuf-V3.0\csharp_unity\Google.Protobuf文件夾拷貝到Unity項(xiàng)目Plugins下面
2逮诲、proto生成的*.cs代碼目錄:Scripts\ResData
3帜平、表格生成的*.bin數(shù)據(jù)目錄:StreamingAssets\DataConfig
4、參考代碼示例:
usingSystem;
usingSystem.IO;
usingUnityEngine;
usingGoogle.Protobuf;
namespaceAssets.Scripts.ResData
{
classResDataManager
{
privatestaticResDataManagersInstance;
publicstaticResDataManagerInstance
{
get
{
if(null== sInstance)
{
sInstance =newResDataManager();
}
returnsInstance;
}
}
publicbyte[] ReadDataConfig(stringFileName)
{
FileStreamfs = GetDataFileStream(FileName);
if(null!= fs)
{
byte[] bytes =newbyte[(int)fs.Length];
fs.Read(bytes, 0, (int)fs.Length);
fs.Close();
returnbytes;
}
returnnull;
}
privateFileStreamGetDataFileStream(stringfileName)
{
stringfilePath = GetDataConfigPath(fileName);
if(File.Exists(filePath))
{
FileStreamfs =newFileStream(filePath,FileMode.Open);
returnfs;
}
returnnull;
}
privatestringGetDataConfigPath(stringfileName)
{
returnApplication.streamingAssetsPath +"/DataConfig/"+ fileName;
}
}
}
讀取二進(jìn)制數(shù)據(jù)示例:
//GOODS_INFO_ARRAY對(duì)應(yīng)的結(jié)構(gòu):GOODS_INFO
GOODS_INFO_ARRAYarr =GOODS_INFO_ARRAY.Parser.ParseFrom(ResDataManager.Instance.ReadDataConfig("Goods.bin"));