Child already added

Hello everyone.
I am using the barebones “new Project”, where I simply changed code in HellowWorldScene to include a tilemap. The init() looks like this:

bool HelloWorldScene::init() {
    if ( !Scene::init()) return false;

    auto tileMap = TMXTiledMap::create("tilemaps/tilemapHD.tmx");
    auto background = tileMap->getLayer("background");

    this->addChild(background, -1);
    background->setAnchorPoint(Point(0.5,0.5));

    return true;
}

However, running this code yields the following assertion error:

Assert failed: child already added. It can't be added again

I am really confused now, as this is really the only thing I’ve changed. Building as a release works without problem, but I can’t run the Debug build this way.
Is there anything I oversee in the sense that cocos “somehow” adds the background if you create the tilemap?

Thank you very much!

This is not necessary as TIleLayer is part of TileMap.
You can hide/show Layer with setVisible, not need to add manually.

2 Likes

Hello,
I wrote the code according to a cocos tutorial online. Apparently not a good one :wink:
Your code works without problems! I still do not really understand why adding the background directly would result in this error…
But I’ll take it as it is :+1:

Thank you very much.

What tutorial did you follow so we can take a look

While browsing back to the tutorial I noticed that I misread the code they used.
I am sorry, this was my fault.

What tutorial did you use so we can take a look?