Removing a Spatial from it's parent

So I have code that is basically this:

private void remove(Spatial entity) {
    entity.getParent().detachChild(entity);
}

Whenever it runs it returns a NullPointerException, and I don’t know why, there’s nothing that should do that, right?

It will if parent is null.

Use entity.removeFromParent(), it’s easier.
Also for a NPE you simply check each variable for null.
In your case either entity or .getParent() is null.

I guess the Parent might be null, because your entity doesn’t have a Node.

That could be why, but looking through my code I don’t see any reason why it wouldn’t have a parent.

Or entity.

Step 1 in debugging: verify assumptions.

…in this case that would solve the problem. Some developers even learn to reflexively check their inputs and throw better exceptions on error.

I would also like to point out that occasional exploration through the javadoc may add new items to your repertoire.
https://javadoc.jmonkeyengine.org/com/jme3/scene/Spatial.html#removeFromParent()

Edit: ninja’d… but my point still stands. First thing one does when “I got an NPE”… see which reference is null with some debugging. Before forum, before anything.

1 Like

What i call compound lines of code, like Bob.getThing().findThat().setThis() are pretty evil when it comes to debug. It is the first thing that gets broken into lines once a NPE pops up.

I would also like to add that there is even the source. I have found that when javadoc wasn’t enough the source was. It is quite well written and clear especially for a project of this size.

It would seem that the parent is null because when I use entity.removeFromParent(); it returns null, but when i do this:

private void remove(Spatial entity) {
    String name = entity.getName();
    NPC.detachChildNamed(name);
}

It doesn’t return null

Well, you live in a different dimension maybe because removeFromParent() returns true or false.

Then you have multiple children with the same name and the one you passed is different than the one that is a child. Or the parent of the passed entity is different than NPC.

…so many things could be happening that one or two System.out.println() would show you instantly. Or just step through in a debugger.

1 Like