J W J W - 4 months ago 33
Java Question

libGDX label sometimes stops when updating every millisecond

I'm trying to update a label every millisecond in libGDX for a set amount of time.

However, sometimes the label suddenly stops without an error OR I receive a "String index out of range" error which then crashes my program. These are two separate issues.

Code:

Stage stage;
Timer timer = new Timer();
Label countUpLabel;
int countUp;

@Override
public void create () {

stage = new Stage(new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()));

//Setting up time label
BitmapFont font = new BitmapFont(Gdx.files.internal("04b_19__-32.fnt"));
LabelStyle labelStyle = new LabelStyle(font, Color.WHITE);
countUpLabel = new Label("Time:\n00000", labelStyle);

countUpLabel.setPosition(200,200);
countUpLabel.setAlignment(Align.center);
countUpLabel.setFontScale(3);

stage.addActor(countUpLabel);

//Setting up timer
timer.schedule(new TimerTask() {
@Override
public void run() {

if (countUp < 3000) {
countUp++;
countUpLabel.setText(String.format("Time:\n%d", countUp));
}else
timer.cancel();

}
}, 0, 1); //every millisecond run the timer
}


Thanks in advance.

Answer

Most of libGDX is not thread safe, unless explicitly stated that it is. Also, updating a label every millisecond, while it is only shown about every 16 milliseconds (the refresh rate of your typical display device), isn't a very good approach. So you might want to remove your timer and instead update the label when it is actually visible: in the render method:

float counter = 0f;
@Override
public void render() {
    if (counter < 3) {
        counter += Gdx.graphics.getDeltaTime();
        countUpLabel.setText(String.format("Time:\n%01.22f", counter));
    }
    // call glClear, stage.act, stage.draw, etc.
}
Comments