Cocos2D-X - EXC_BAD_ACCESS (code=2, address=0x0) when initializing a CCTMXTiledMap

落爺英雄遲暮 提交于 2020-01-03 05:20:08

问题


I'm trying to create a game in Cocos2D-X with a tile map and I'm getting the below error:

EXC_BAD_ACCESS (code=2, address=0x0) in the line setContentSize(CCSizeZero); of the method CCTMXTiledMap::initWithTMXFile(const char *tmxFile)

I'm creating the tile map in this way:

tileMap->initWithTMXFile("TileMap.tmx");
this->background = tileMap->layerNamed("Background");

Somebody knows what it's happening?

Please, could you help me?


回答1:


Ok, I've found the problem. Just a little of theory:

EXC_BAD_ACCESS code=2 means that the pointer is corrupt and this could happen because:

  • The pointer could have never been initialized.
  • The pointer could have been accidentally written over because you overstepped the bounds of an array.
  • The pointer could be part of an object that was casted incorrectly, and then written to.
  • Any of the above could have corrupted a different pointer that now points at or near this pointer, and using that one corrupts this one (and so on).

So, in my case, I thought that initWithTMXFile was good enough to initialize the tileMap pointer but I was wrong. The solution is that first thing before initWithTMXFile, tileMap must be initialized. So, the correct block of code is:

this->tileMap = new CCTMXTiledMap();
this->tileMap->initWithTMXFile("TileMap.tmx");
this->background = tileMap->layerNamed("Background");
this->addChild(tileMap);

I hope it helps.



来源:https://stackoverflow.com/questions/16363513/cocos2d-x-exc-bad-access-code-2-address-0x0-when-initializing-a-cctmxtiledm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!