天天看點

CocosCreator protobufjs搭建

如果從來沒有使用過protobufjs的同學,建議去官網的github上看一下的裡面的Examples(打開網站後,ctrl+f這樣搜會比較快)。

這之後,需要把xxx.proto檔案放到resources檔案夾下,因為這個要動态加載。

至于網上的一些文章,說的是proto2.0的版本,但是現在基本上都是用3.0,接口不一樣。

如果項目隻需要建立在網站上,而不需要打包成app,那可以用

function callback(err, root) {

};
var url = cc.url.raw("resources/proto/addressbook.proto");
protobuf.load(url, callback);
           

來解決。

我的檔案是放在resources下的proto檔案夾裡。

如果需要打包成原生app,則:

var url = cc.url.raw("resources/proto/addressbook.proto");
cc.loader.load(url,function(err,tex){
    var protobuf = require('protobufjs');
    var pr = protobuf.parse(tex);
    var Person = pr.root.lookup("com.protobuf.Person");
    var PhoneNumber = pr.root.lookup("com.blst.protobuf.Person.PhoneNumber");
    var phoneNum = PhoneNumber.create({number:"13811113369"});
    var message = Person.create({
        name: "names",
        id: 100001,
        phones:[phoneNum]
    });
    var buffer = Person.encode(message).finish();

    var message1 = Person.decode(buffer);
    cc.log(" number = " + message1.phones[0].number);
});
下面是proto 内容
syntax = "proto3";
package com.protobuf;

message Person {
    string name = 1;
    int32 id = 2; 
    string email = 3;

    enum PhoneType {
        MOBILE = 0;
        HOME = 1;
       WORK = 2;
    }

    message PhoneNumber {
        string number = 1;
        PhoneType type = 2;
    }

    repeated PhoneNumber phones = 4;
}
           

總的來說,還是第二種方法全面。

文章參考:http://forum.cocos.com/t/cocos-creator-protobuf/48467