Search code examples
javaandroidlibgdxactorstage

Stage will not render in libgdx, get null pointer error


I am just trying to get Actor and Stage to work properly to set up a basic flow and then move on from there. I get a null pointer to stage every time, help please. The Paddle and Ball class are identical right now, Assets is a static class for loading textures.

public class MyGame implements ApplicationListener {
public final static int WIDTH = 480;
public final static int HEIGHT = 800;
private Stage stage;
private Paddle paddle;
private Ball ball;




@Override
public void create () {
    Assets.load();
    Stage stage = new Stage(new ScreenViewport());
    paddle = new Paddle();
    ball = new Ball();
    stage.addActor(paddle);
    stage.addActor(ball);


}

@Override
public void render() {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    stage.draw();

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void resize(int width, int height){
    stage.getViewport().update(width,height,true);

}

@Override
public void dispose(){
    Assets.dispose();
    stage.dispose();


}

public int getWidth(){return WIDTH;}
public int getHeight(){return HEIGHT;}

}

public class Paddle extends Actor {


Rectangle bounds;


public Paddle(){

    setPosition(150,10);


}

@Override
public void act(float delta){

}


public void draw(Batch batch , float parentAlpha){

    batch.draw(Assets.paddle,150,10 );
}

private void updateBounds() {bounds.set(getX(), getY(), getWidth(), getHeight());
}
public Rectangle getBounds() {
    return bounds;
}

}


Solution

  • The problem is, that you create a Stage in the create method, but you never asign it to your private member stage.
    So instead of writing Stage stage = new Stage() in the create just write stage = new Stage().
    Also remember to add the Exception and it's Stack Trace to your SO-Question and mark the line in which the Exception seems to occure. It will make it much easier for everybody who wants to help.