egret5.x修改了第三方庫的導入方式,新建項目的index.html再也看不到任何庫的預留位置。取而代之,從manifest.json去讀取並加載庫和游戲文件。因此,這里的配置已經不能像之前項目非標准的配置方式了,所有的庫都要在egret項目下egretProperties.json文件中去配置。
protobuf的API發生了翻天覆地的改變,因此需要重新熟悉,不過好在有官方文檔熟悉起來也不難。現在也不需要再去為再egret中使用自己去寫.d.ts聲明了,在protobuf庫下index.d.ts已經寫好了。我們只需要拷貝到項目中使用即可。
在egret中,我在libs下創建一個protobuf文件夾,然后將index.d.ts拷貝到里面,並改名為protobuf.d.ts,再將protobuf庫下dist目錄中將protobuf.js和protobuf.min.js文件拷貝到這里。然后在項目下egretProperties.json配置protobuf庫,如下
{
"native": {
"path_ignore": []
},
"publish": {
"web": 0,
"native": 1,
"path": "bin-release"
},
"egret_version": "5.0.7",
"template": {},
"modules": [
{
"name": "egret"
},
{
"name": "game"
},
{
"name": "tween"
},
{
"name": "res"
},
{
"name": "promise",
"path": "./promise"
},
{
"name": "protobuf",
"path": "./libs/protobuf"
}
]
然后在resource/assets下創建一個proto文件夾,專門存放proto,在這里我創建了一個login.proto
syntax = "proto2";
package login;
message Login {
required string account = 1;
required string password = 2;
}
message createRole {
required string name = 1;
required int sex = 2;
}
然后在default.res.json中配置,這里我就配成預加載了,當然每個項目的處理不一樣,這就仁者見仁智者見智了
{
"groups":[
{
"keys":"bg_jpg,egret_icon_png,description_json,login_proto",
"name":"preload"
}],
"resources":[
{
"name":"bg_jpg",
"type":"image",
"url":"assets/bg.jpg"
},
{
"name":"egret_icon_png",
"type":"image",
"url":"assets/egret_icon.png"
},
{
"name":"login_proto",
"type":"text",
"url":"assets/proto/login.proto"
},
{
"name":"description_json",
"type":"json",
"url":"config/description.json"
}]
}
然后開始在Main.ts中編寫代碼,在createGameScen中編寫了如下測試代碼
let ProtoBufRoot = new protobuf.Root();
let loginStr:string = RES.getRes("login_proto");
protobuf.parse(loginStr, ProtoBufRoot);
const Login = ProtoBufRoot.lookupType("login.Login");
let message = Login.create({ account: "qiu" , password: "204qiu"});
console.log(`message = ${JSON.stringify(message)}`);
let buffer = Login.encode(message).finish();
console.log(`buffer = ${Array.prototype.toString.call(buffer)}`);
let decoded = Login.decode(buffer);
console.log(`decoded = ${JSON.stringify(decoded)}`);
一般我都會將ProtoBufRoot作為全局存放,這樣引用方便,所以首字母大寫了。當然我自己也是將其作為全局存放的,這里為了不將代碼分散看起來凌亂,放在一起方便查看,只是拋磚引玉。
編譯運行即可看到編碼和解碼的結果
message = {"account":"qiu","password":"204qiu"}
buffer = 10,3,113,105,117,18,6,50,48,52,113,105,117
decoded = {"account":"qiu","password":"204qiu"}