Check if spatial has userData

I use object picking in my game, all collision results are geometries. If I have a loaded model, it contains multiple Geometries.
If you have a simple Spatial, you can get the name with spatial.getName();
Now when I pick a loaded model, I get multiple collisions of course. I take the closest collision and use the following method to find the right Spatial which represents the “3d object” which is clicked on by the user.

private Spatial loadedModelOf(Spatial picked) {

Spatial iter = picked;

while(iter != null && iter.getUserData("id") == null) {
    iter = iter.getParent();

return iter;


If I load a model with the assetManager I get a spatial object, I set the userdata “id” to that spatial (id is a number to identify the game item), and give it a name with setName();
When I pick that object with object picking I want to get the right spatial back to get the userdata and the name.
I am doing this with the method above. But it’s throwing nullPointerExceptions. I only want to check if the iter object has the userDataKey “id”. Which indicates it’s a loaded model.

You can get a NPE when you pick a spatial which isn’t a child of a spatial with a set id. Then you return null, because you iterate until you get the parent of rootnode, which is null. You could check if iter==null before you return it and maybe throw a custom exception or handle it in another way.

1 Like