Geometry cannot be cast Error


im working on a game where i can interact with objects, like i.e. trees. I already managed to load a wavefront .obj into my map with no problems:


private void addTreeTest(){

Geometry test = (Geometry) main.getAssetManager().loadModel("Models/test.obj");


test.setLocalTranslation(20, getHeightAt(20, 20), 20);

test.scale(1, 1, 1);


RigidBodyControl testcon = new RigidBodyControl(CollisionShapeFactory.createMeshShape(test), 0);





But now i need to have attributes in that Geometry, like health to know when a tree is cut down. I created a class which extends Geometry

and inserted it into my code:


mygame.Objects.Object test = (mygame.Objects.Object) main.getAssetManager().loadModel("Models/test.obj");


The mygame.Objects.Object class just extends the Geometry class, there is nothing else in it. But when i try to run the game i get:

Uncaught exception thrown in Thread[LWJGL Renderer Thread,5,main]

java.lang.ClassCastException: com.jme3.scene.Geometry cannot be cast to mygame.Objects.Object

thx for any help

This is an inheritance problem, the “is a” fundamental OOP feature. You have, Geometry → Object. An Object “is a” Geometry, but a Geometry is not an Object. Better to have a class which contains the Geometry using composition “has a”, and add all the features, life etc to that class, or use setUserdata(), to attach it directly to the spatial.

thx for the fast reply,

i didnt see the setuserdata, sounds like a good way. the other option is not so good, because i wanted to “get the nearest object on click”, and since i get a spatial from it, i cant hold the information in an external class which cant be attached to a node. ill try it with the user data, thx again

yeh setUserData/getUserData will definitely help you there. You should even be able to attach your “Object” to it.

[java]Object object = new Object();


spatial.setUserData(“object”, object);

Object object1 = (Object) spatial.getUserData(“object”);




works fine now for me. if anyone else is going to realize it in this way, the object which is given to the userdata must implement the savable interface.

1 Like