Check whether a texture is being used

Does anyone know of a good way to check whether a texture is being used?

I dynamically add and remove meshes from the scene.

I need to be able to remove unused textures from the cash to avoid running out of memory.

I didn't know that if I load the same texture twice it just grabs it from the cache, which is great, so up til now I have just deleted the texture from the cash when the mesh is removed. This results in that all objects using that texture turns white of course.

The Texture object or other objects themselves don't track who they are being used by. You have to options, implement some basic "reference counting" (keep a counter for each texture, increase it when an object uses it, decrease when an object using it is destroyed), or iterate through your entire scene, check which textures are in use and compare these to what's in the cache.


What does doTextureCleanup() in TextureManager do?

Ok, I went for iterating the scene.

I made this for checking if a texture is in use:

    public static boolean usesTexture(Texture texture, Spatial spatial){
        TextureState ts = (TextureState)spatial.getRenderState(RenderState.RS_TEXTURE);
            for(int i = 0;i<ts.getNumberOfSetTextures();i++){
                    return true;
        if(spatial instanceof Node){
            for(int i = 0;i<((Node)spatial).getQuantity();i++){
                if(usesTexture(texture, ((Node)spatial).getChild(i))){
                    return true;
        return false;

Yes… bit heavy for checking a lot of textures like that. Better make sure you check all the textures at once, and don't use it more than needed.

Yes, it would be better not having to iterate through the meshes everytime. However in my case they aren't that many and it doesn't happen very often + I can't notice any delay so I'll stick with it until it becomes a problem.