Search code examples
javalibgdx

How to dispose Libgdx Texture via Sprite object


The standad way of creating a sprite in LibGDX is this

Texture texture = new Texture(Gdx.files.internal("myTexture.jpb");
Srite sprite = new Sprite(texture);

There is also another shorter way

Sprite sprite = new Sprite(new Texture(Gdx.files.internal("myTexture.jpb"));

Now the second way is much more efficient as when you use a lot of different textures and sprites it really saves a lot of lines of code. The problem though, is that I can't find a way to dispose the textures that the sprites use when I don't need them anymore, as the the Sprite class does not implement the Disposable interface and thus it does't have a dispose() function.

Can you think of any way I can dispose the Texture given the fact that I don't have a direct reference to it like I do if I choose the first way of declaration?


Solution

  • A Sprite is a subclass of TextureRegion, so it has a getTexture() method to get at the underlying texture object.

    The Sprite API docs make this pretty obtuse (its just referenced in the "Methods inherited from .." section).