如果我调用sprite.getTexture().dispose();
从 aTexture
中检索到的a ,则TextureAtlas
整个屏幕都会变黑。
public class PlayState extends State {
// The falling objects from the sky
private Array<FallingObject> objects;
private AssetManager assetManager;
private TextureAtlas textureAtlas;
private Sprite background;
public PlayState() {
assetManager = new AssetManager();
assetManager.load("assets.pack", TextureAtlas.class);
assetManager.finishLoading();
textureAtlas = assetManager.get("assets.pack");
background = new Sprite(textureAtlas.get("background"));
// Add some falling objects
objects.add(new FallingObject(textureAtlas.findRegion("kitty")));
objects.add(new FallingObject(textureAtlas.findRegion("leaf")));
ojbects.add(new FallingObject(textureAtlas.findRegion("dog")));
}
@Override
public void update(float deltaTime) {
for (FallingObject object : objects) {
object.update(deltaTime);
if (object.reachedBottom()) {
object.dispose(); // <------------ THIS CAUSES THE ERROR
objects.remove(object);
objects.add(new FallingObject(textureAtlas.findRegion(getRandomRegionName()));
}
}
}
@Override
public void render(SpriteBatch batch) {
batch.begin();
// Draw the background
background.draw(batch);
// Draw the falling objects
for (FallingObject object : objects) {
batch.draw(object.getSprite(), object.position.x, object.position.y);
}
batch.end();
}
@Override
public void dispose() {
assetManager.dispose();
textureAtlas.dipose();
for (FallingObject object : objects) {
object.dispose();
}
}
}
坠落的物体
public class FallingObject extends GameObject {
private Sprite sprite;
public FallingObject(TextureRegion region) {
sprite = new Sprite(region);
}
public void dispose() {
sprite.getTexture().dispose(); // <-- HERE, when this is called, the whole screen becomes black
}
}
我已经设法解决了这个问题,方法是不调用从课堂dispose
上texture
检索到的sprite
内容。FallingObject
我通过声明NULL
精灵来清除引用:
public class FallingObject extends GameObject {
private Sprite sprite;
public void dispose() {
sprite = null;
}
}
但现在我害怕内存泄漏!这是处置 Sprite 的正确方法吗?