1)protobuf.js項目
https://github.com/protobufjs/protobuf.js
2)引入protobuf.js到ts項目中
將此js文件以插件形式導入creator中,勾選:允許編輯器加載
3)由於protobuf是js文件,我們項目是ts,所以要允許ts中調用js的代碼
方法一、自己寫global.d.ts(推薦)
// 自定義
declare const protobuf: any;
// end
方法二、或者直接把這句話寫到creator.d.ts中
方法三、import protobuf = require("路徑/protobuf");
4)動態加載
import GameApp from "./Game/GameApp";
import ProtoMgr from "./Managers/Net/ProtoMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class GameLanch extends cc.Component {
onLoad(): void {
// 初始化框架模塊: 網絡模塊、資源管理模塊,協議模塊
// end
this.node.addComponent(ProtoMgr);
// 遊戲模塊
this.node.addComponent(GameApp);
// end
}
start(): void {
cc.loader.loadRes("Proto/game.proto", (err, pbTextAsset) => {
// 加載pb
let pb = protobuf.parse(pbTextAsset);
ProtoMgr.Instance.setPb(pb);
// 切換場景
GameApp.Instance.GameStart();
});
}
}
5)封裝編解碼器
const {ccclass, property} = cc._decorator;
@ccclass
export default class ProtoMgr extends cc.Component {
public static Instance: ProtoMgr = null;
private pb: any = null;
onLoad(): void {
if (ProtoMgr.Instance == null) {
ProtoMgr.Instance = this;
} else {
this.destroy();
return;
}
}
public setPb(pb): void{
this.pb = pb
}
public SerializeMsg(msgName, msgBody): Uint8Array {
let rs = this.pb.root.lookupType(msgName);
let msg = rs.create(msgBody);
let buf = rs.encode(msg).finish();
return buf;
}
public DeserializeMsg(msgName, msgBuf: Uint8Array): any {
let rs = this.pb.root.lookupType(msgName);
let msg = rs.decode(msgBuf);
return msg;
}
}
6)使用
import ProtoMgr from "../Managers/Net/ProtoMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class GameApp extends cc.Component {
public static Instance: GameApp = null;
onLoad() {
if (GameApp.Instance == null) {
GameApp.Instance = this;
} else {
this.destroy();
return;
}
}
public GameStart(): void {
// 進入遊戲邏輯
this.EnterGameScene();
// end
}
public EnterGameScene(): void {
// test
let msg = {uname: "blaker", upwd: "upwd"};
// 對象-->編碼-->二進制
let buf = ProtoMgr.Instance.SerializeMsg("UnameLoginReq", msg);
cc.log(buf);
// 二進制-->解碼-->對象
let obj = ProtoMgr.Instance.DeserializeMsg("UnameLoginReq", buf);
cc.log(obj);
// end
// 釋放地圖
// end
// 釋放角色
// end
// 釋放UI
// end
}
}