Search code examples
javaanimationnullpointerexceptionblenderjmonkeyengine

Jmonkey NullPointerException


This is my code to load a node with a model then attach an animation control. I get a NullPointerException because it is saying my AnimControl is null.

My anim control class is in Models/stickman.blend/Armature/Cube

Node model = (Node)assetManager.loadModel("Models/stickman.j3o");
control = model.getControl(AnimControl.class);
control.addListener(this);
channel = control.createChannel();
channel.setAnim("jump");
model.scale(0.25f);
model.addControl(physicsCharacter);
getPhysicsSpace().add(physicsCharacter);
rootNode.attachChild(model);

How do I get rid of this nullpointerexception or move the AnimControl class up out of the sub directory so it won't be null? Thanks.

java.lang.NullPointerException
at mygame.Main.simpleInitApp(Main.java:96)
at com.jme3.app.SimpleApplication.initialize(SimpleApplication.java:226)
at com.jme3.system.lwjgl.LwjglAbstractDisplay.initInThread(LwjglAbstractDisplay.java:130)
at com.jme3.system.lwjgl.LwjglAbstractDisplay.run(LwjglAbstractDisplay.java:207)
at java.lang.Thread.run(Thread.java:744)

enter image description here


Solution

  • The NullPointerException is telling you as clearly as it can that the variable control is null. This in turn means that model.getControl(AnimControl.class); has returned null. The javadoc tells you it will do this if there is no control of type AnimControl.class

    I think, looking at the tutorial, that you must attach your Node to the rootNode. From this page

    Every JME3 application has a rootNode: Your game automatically inherits the rootNode object from SimpleApplication.

    So, as long as your class extends SimpleApplication you just need to add

    rootNode.attachChild(model);
    

    immediately after

    Node model = (Node)assetManager.loadModel("Models/stickman.j3o");
    

    It seems that this attachment will automatically associate your model with a control - as demonstrated in this snippet from the animation beginners tutorial

    player = (Node) assetManager.loadModel("Models/Oto/Oto.mesh.xml");
    player.setLocalScale(0.5f);
    rootNode.attachChild(player);
    control = player.getControl(AnimControl.class);