How to change sprite parent?

How to change sprite parent?
0.0 0



When i trying to change parent of sprite by removeChild and then addChild on other sprite i getting this error

Plese help me to solve the problem. Thanks.


You should paste the source code where raise this crash.


This piece of code don’t actually have many sence for my game, but im trying make work at least this.
Here im trying to change parent of spriteShadow from my main scene layer to spritePiece, and i expect that spriteShadow will move and rotate with spritePiece - just so simple:

void MyGame::ccTouchesEnded(CCSet* touches, CCEvent* event) {
    CCPoint location = convertTouchToNodeSpace((CCTouch*)touches->anyObject());
    if(pieceWasSelected) {
        removeChild(Pieces[pieceSelectedID].spriteShadow, false);
        Pieces[pieceSelectedID].spritePiece->addChild(Pieces[pieceSelectedID].spriteShadow); // << -- Crash here

‘Pieces’ here is std vector which keep class which contain sprites.

Game crash at this line in CCNode.cpp file:

void CCNode::addChild(CCNode *child, int zOrder, int tag) { 
    CCAssert( child != NULL, "Argument must be non-nil");
    CCAssert( child->m_pParent == NULL, "child already added. It can't be added again"); // << -- HERE


Solved with retain() funtion.
My version of cocos2d is 1.0.1.


Thanks Andrey, I faced this problem too and was able to resolve it. In my case, it was removing and adding to the same parent. But, I am still unclear why it occurs.


i just know that we should retain the sprite before we remove it from his parent and then release it after we add it to another sprite as a child.
and againg: never forget call release() after each retain()