AbstractControl getUserData of spatial

Hey all!
I’ve been following the beginner’s guide book, and have just finished the controls chapter. Controls work perfectly fine, however, when I try setting userData, using setUserData to a geometry that I later on add the control to, I am unable to access this data within the control itself through the inherited spatial object. I always get a null pointer exception thrown for some reason.

This is my code:
[java]Box tower = new Box(1,3f,1);
Geometry towerGeo = new Geometry(name, tower);

    Material towerMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    towerMat.setColor("Color", color);
    
    towerGeo.setMaterial(towerMat);
    towerGeo.setLocalTranslation(loc);
    towerGeo.move(0, 3f, 0);
    
    towerGeo.setUserData("Index", index);
    towerGeo.setUserData("Charges", 100);
    towerGeo.setUserData("Height", 6);
    towerGeo.addControl(new TowerControl(this));
    
    towerNode.attachChild(towerGeo);[/java] 

And the control:
[java]public TowerControl(GameplayAppState gameplayAppState){
this.gameplayAppState = gameplayAppState;
this.index = (Integer)spatial.getUserData(“Index”);
this.charges = (Integer)spatial.getUserData(“Charges”);
this.height = (Float)spatial.getUserData(“Height”);
}[/java]

I’m not sure what I’m doing wrong, and would really appreciate it if someone could point me in the right way!

Before the control is added to a Spatial, which spatial do you think it would refer to?

The constructor for TowerControl is run before the control has been added so there is no spatial yet. You could override setSpatial() to grab the user data you are interested in but remember to call super.setSpatial() first in the override.