MaxGyver
MaxGyver

Reputation: 437

LibGDX: Create and dispose ShapeRenderer in render method?

I'm using a ShapeRenderer object to create a color gradient in my game (Screen class). The allocated memory used to grow permanently until I started to dispose my ShapeRenderer object after every call. How can I reuse my color gradient? Is there a way to paint the gradient into a texture (only once for reuse in the render method)?

public void render(float deltaTime) {
    camera.update();
    batch.setProjectionMatrix(camera.combined);

    ShapeRenderer shapeRenderer = new ShapeRenderer();
    shapeRenderer.setProjectionMatrix(camera.combined);
    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
    shapeRenderer.rect(0, 0, screenWidth, screenHeight, topColor, topColor, bottomColor, bottomColor);
    shapeRenderer.end();
    shapeRenderer.dispose();

    batch.begin();
    ...
    batch.end();
}

Upvotes: 0

Views: 790

Answers (1)

StrongJoshua
StrongJoshua

Reputation: 995

Although it seems you have solved your problem, here is just a little note for you and anyone stumbling across this post with a similar question.

Do not instantiate new Objects (of any type) during every run through a loop, at all costs. The reason you were experiencing slow-down is because of exactly this. Every time you instantiate a new object and then stop using it, the JVM's Garbage Collector needs to get rid of that Object. You should always try to reuse objects. This is why pools and memory management in general (these links are for LibGdx specificially) are so important.

Your notion to make a field for the ShapeRenderer was a good one, just don't forget to dispose() it in your game's dispose() method.

Upvotes: 3

Related Questions