LibGDX - Should texture.dispose() execute first and then batch.dispose()? or no different?
I have the following simple code. My question is should texture.dispose(); execute first and then batch.dispose() in dispose() method?
It is because we pass a texture reference in sprite=new Sprite(texture); and then sprite.draw(batch);
If texture does not destroy first, the sprite or batch can't be destroyed. Is it related to reference counting?
Here is the LibGDX Assetmanger offical site (I will try Assetmanager at next stage):
Disposing Assets
Easy again, and here you can see the real power of the AssetManager:
manager.unload("data/myfont.fnt");
If that font references a Texture that you loaded manually before, the texture won't get destroyed! It will be reference counted, getting one reference from the bitmap font and another from itself. As long as this count is not zero, the texture won't be disposed.
package com.program.mydemo;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class MyDemo extends ApplicationAdapter {
SpriteBatch batch;
Texture texture;
Sprite sprite;
@Override
public void create () {
batch = new SpriteBatch();
texture = new Texture("bg.png");
sprite=new Sprite(texture);
}
@Override
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
sprite.draw(batch);
batch.end();
}
@Override
public void dispose() {
batch.dispose();
texture.dispose();
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
}
batch.dispose()
will dispose only batch internal resources (thing ofShaderProgram
etc).texture.dispose();
will dispose individual texture.It doesn't matter which dispose you call first. They dispose unrelated resources. But you cannot use disposed texture anymore. Calling
sprite.draw(batch);
will not work with disposed texture.The
AssetManager
counts only references to assets loaded by it. No need to consider it here.Update for
Stage
:From source:
Calling
dispose()
on instance ofStage
will dispose its inner batch and clears all children (Actors
). I looked into the code a bit deeper and there is no disposing inclear()
methods. So if you want to dispose all the resources used to create the stage. Namely the skin. You need to do manually byunload(...)
ordispose()
methods ofAssetManager
.