- 第一步 sudo npm install -g protobufjs
因爲會涉及到權限問題,sudo 還是有必要加的,提示輸入密碼,即自己的電腦密碼 - 下載protobuf.js https://www.npmjs.com/package/protobufjs
或者在node安裝的 protobufjs 裏面找dict 裏面有 - 導入CocosCreator 爲插件
- 創建自己的proto消息文件
package mytestpackage; syntax = "proto3"; message testRequest { required int32 id = 1; required string name = 2; }
mytestpackage 是自己定義的包名, proto3是用Protobuf3格式
- 在proto文件夾下執行
pbjs -t static-module -w commonjs -o proto.js *.proto(這句代碼可以將文件中所有的.proto文件轉化爲一個proto.js文件)
生成的是 proto.js -
修改 proto.js裏面的代碼
var $protobuf = require("protobuf.js"); - 測試
var packageS = require("./protoBuf/proto.js");// 引用proto.js cc.Class({ extends: cc.Component, // use this for initialization onLoad: function () { var that = this; this.label.string = this.text; var mytestpackage = packageS.mytestpackage; // 獲取測試包名 var message = mytestpackage.testRequest.create({id:1, name: "my first protoBuf example"}) var buffer = mytestpackage.testRequest.encode(message).finish(); this.scheduleOnce(function() { var desc = mytestpackage.testRequest.decode(buffer); console.log('------'); console.log(JSON.stringify(desc)); that.label.string = desc.name; }, 1); }, });
- 看到下面的界面就是成功了