[SOLVED] Children' parent is null?

TL;DR:

 Layer->addChild(child);
 child->setParent(Layer);
  • on buttonPress: child->parent equals null
    --------------------- ¿¿¿¿ WHYYY???---------------------------

Long version:
Hi,
I have a small problem that I dont understand:

step 1: steal nodes from another node
step 2: create physics bodies for all of them
step 3: (fail) remove physics bodies


details:
step 1 & 2

for(Node* child : otherNode->getChildren())
{
	child->setParent(nullptr);
	addChild(child);
	child->setParent(this);
	ApplyPhysics(child);  <--- this just adds the physicsbody
}
otherNode->removeAllChildrenWithCleanup(true);

And… I want to remove All the physics bodies used on THIS layer (I dont want to remove the scene)
So, when I call this:
step 3:
(note: at this point… every child says parent is null)

void GameLayer::Clear()
{
	for(Node* c : getChildren())
	{
		if(PhysicsBody* body = c->getPhysicsBody())
		{
			body->removeFromWorld();
			c->removeComponent(body);
		}
	}
}

I expect the removeFromWorld actually removes from world,but this is not happening,
because somehow… each of the CHILDREN of the Layer… says their PARENT is null

and this doesnt let the bodies to be removed

this is the actual code from cocos2dx PhysicsBody:

void PhysicsBody::removeFromPhysicsWorld()
{
    if (_owner)
    {
        auto scene = _owner->getScene();   <--- this will search recursively for parent
        if (scene)
            scene->getPhysicsWorld()->removeBody(this);
    }
}

So… bodies are never removed, since _owner->getScene() will return null because children say they dont have parent :cry:

The only solution I have found so far is this:

for(Node* c : getChildren())
		c->setParent(this);

and then to remove bodies. (Which I think its stupid… )

why the children set parent null ??
WHEEN?

  1. Why are you using setParent() after addChild()??

Try to use removeFromParent() instead setParent(nullptr).

I think the problem is that otherNode still believes that it has children when you call removeAllChildrenWithCleanup().

1 Like

Indeed… :sleepy: the otherNode is screwing it up. When its removed it sets all its children to SetParent(null) (even if he is not anymore the parent).
RemoveFromParent actually does what i though SetParent(null) would do.
thanks a lot.

You are welcome!

You also do not need to use child->setParent(Layer), Layer->addChild(child) does all the work.

p.s.
Cool avatar!

1 Like