天天看点

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