CocosCreator2D 安裝protoBuf

  1. 第一步 sudo npm install -g protobufjs 
    因爲會涉及到權限問題,sudo 還是有必要加的,提示輸入密碼,即自己的電腦密碼
  2. 下載protobuf.js  https://www.npmjs.com/package/protobufjs
    或者在node安裝的 protobufjs 裏面找dict 裏面有
  3. 導入CocosCreator 爲插件
     
  4. 創建自己的proto消息文件
    package mytestpackage;
    syntax = "proto3";
    
    message testRequest {
        required int32 id = 1;
        required string name = 2;
    }

    mytestpackage 是自己定義的包名, proto3是用Protobuf3格式

  5. 在proto文件夾下執行
    pbjs -t static-module -w commonjs -o proto.js *.proto(這句代碼可以將文件中所有的.proto文件轉化爲一個proto.js文件)
    生成的是 proto.js
  6. 修改 proto.js裏面的代碼 
     var $protobuf = require("protobuf.js");

  7. 測試
     
    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);
        },
    });
  8. 看到下面的界面就是成功了

     
  9.  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章