Reputation: 127
I get a NullPoinerExecption when calling
enemy.getSprite().draw(batch);
Where do I have to initialize my sprite? It works in main class, but if I try to initialize texture and sprite in Enemy constructor then it gives me error.
Here's my main class:
public class SpaceShooter implements ApplicationListener {
private SpriteBatch batch;
private Texture texture;
private Sprite sprite, spriteEnemy;
private Player p;
private Enemy enemy;
@Override
public void create() {
p = new Player();
enemy = new Enemy(spriteEnemy);
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
batch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("craft.png"));
sprite = new Sprite(texture);
sprite.setPosition(w/2 -sprite.getWidth()/2, h/2 - sprite.getHeight()/2);
// Adding enemy sprite
}
@Override
public void dispose() {
batch.dispose();
texture.dispose();
}
@Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// moving sprite left and right
batch.begin();
sprite.draw(batch);
enemy.getSprite().draw(batch);
batch.end();
}
Enemy class
public class Enemy {
private Sprite sprite;
private Texture texture;
boolean gameOver;
public Enemy(Sprite sprite){
this.sprite = new Sprite();
}
public Sprite getSprite(){
return sprite;
}
public void create() {
texture = new Texture(Gdx.files.internal("enemy.png"));
sprite = new Sprite(texture);
this.sprite.setPosition(100, 200);
}
Upvotes: 0
Views: 6690
Reputation: 93571
You never called create()
on your Enemy instance, so the texture and sprite in Enemy are never instantiated. Call enemy.create()
in your create()
method. Or simplify things and move the code in enemy.create()
into the Enemy constructor.
Also, in your Enemy constructor, you are instantiating a useless Sprite instance that does not reference a Texture and which will be thrown away once create()
is called on the enemy. And the constructor does not even use the Sprite reference that's passed in (although you are currently just passing in null
anyway because spriteEnemy
in the SpaceShooter class is never instantiated).
Upvotes: 2