Cocos Creator: Loading TMX Files dynamically

I’m trying to load a TMX file dynamically.

I followed the first response on this post here.

This is what my code looks like:

 var theMap = new cc.TiledMap();
        cc.loader.loadRes("testlevel1", cc.TiledMapAsset, function (err, mapAsset) {
       cc.log(mapAsset);
               cc.log(theMap);

        theMap.tmxAsset = mapAsset;
});

I’m getting an error that looks like this.

Any ideas as to what is producing this error? I know when I comment or remove this line of code theMap.tmxAsset = mapAsset; The error goes away, but I need to assign the TiledMapAsset to the TiledMap so I can work with it!

Please don’t using a component by new one. You should get a component object by this way:

var theMap = theNode.getComponent(cc.TiledMap);
if (!theMap) {
    theMap = theNode.addComponent(cc.TiledMap);
}
1 Like

Out of curiosity why can’t I use new?

Do I need to create the cc.TileMap in the properties sections at the top of the script?

Because the initialization of cc.TiledMap component using the property this.node. And the property will be correctly initialized when theNode.addComponent(cc.TiledMap) is invoked.

1 Like