How to transfer a child node from one node to another?

Hi everyone!

There are the Sprite1 and the Sprite2 in my scene. The Sprite1 has a child the Sprite3.
At some point, I need to the Sprite3 has become a child node for the Sprite2. And now had no connection with Sprite1.

I’m a little confused Cocos memory management system.
So I would like to know - will be faithful the following code?

auto Sprite1 = Sprite::create();
auto Sprite2 = Sprite::create();
auto Sprite3 = Sprite::create();

Sprite1->addChild(Sprite3, 0, 0);

// After some time in another function

Sprite2->addChild(Sprite1->getChildByTag(0), 0, 0);
Sprite1->removeChildByTag(0, false);

I do it right?
And there will be any problems, because of this in the future?

I highly appreciate any advice. Thank you.

You must remove child first, otherwise you’ll get a failed assertion.

Thank you for your response! :smile:
But I do not quite understand what you mean by “failed assertion”.

I looked at the source code, and apparently not the addChild() was to be held. But I tried this code and it seems to work because the Sprite3 is displayed in the right place now.
I’m just not sure it will not cause problems in the future.

Ok, if I femoveChild first,
the system will not release the memory allocated by the Sprite3 before I call the method addChild a second time?

Check CCNode.cpp, the body of Node::addChild (line 742 in my version):

CCASSERT( child->_parent == nullptr, "child already added. It can't be added again");

It means that the child mustn’t have a parent when you’re adding it to another node as a child.
The engine won’t release the memory before removeChild(…) and addChild(…) calls, because it does it at the end of the frame when the scene is already rendered.

1 Like

Yes this is the line of code that confused me.
But then strange that my example code is works.

In any case, you calmed me down. I will remove nodes first. Thank you very much)