Reputation: 45
I'm trying to create a simple BreakOut clone to familiarize myself with LibGDX and scene2d. However, after assembling a very basic example to get myself started, I'm getting a NullPointerException on a very clearly defined object.
I have an Actor class called Paddle that has an instance in my program called, simply enough, paddle. It is declared as a global variable and initialized in the create() method. When I run the program, it returns an error in my render() method in the code that checks if the paddle is outside the bounds of the screen:
// make sure the paddle stays within the bounds of the screen
if(paddle.getX() < 0) paddle.setX(0); // <--- error is detected here
if(paddle.getX() > 800 - 200) paddle.setX(600);
Here is the error returned:
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: java.lang.NullPointerException
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:111)
Caused by: java.lang.NullPointerException
at com.freakout.Game.render(Game.java:150)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:190)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:108)
And here's the Paddle class;
public class Paddle extends Actor {
TextureRegion region;
public Paddle(){
region = new TextureRegion(new Texture(Gdx.files.internal("paddle.png")), 800/2 - 200 /2, 20);
}
}
Here's the code in case it helps to look at the whole thing.
EDIT: I found the answer thanks to the comments: I realized what I had missed immediately after posting- looks like I redefined the scope of the paddle variable (by using Paddle paddle = new Paddle(...)) to be local to the method instead of global. Therefore, when it attempted to access the object, it always returned null because the object was inaccessible outside the create() method.
If you're having issues with your Actors not working correctly on basic calls, that might be your culprit.
Upvotes: 1
Views: 710
Reputation: 7126
I have gone through your code and I found that in your create()
method you created a Paddle by "new Paddle()
" and assigned it to a local variable "paddle
" in this line "Paddle paddle = new Paddle();
". So actually because of this the variable named "paddle
" of the Game class remains uninitialized (because of being hidden by the local variable of the method). So when it is accessed in your render()
method, you get NullPointerException
.
To get rid of this thing just turn "Paddle paddle = new Paddle();
" this line to "paddle = new Paddle();
" and you are done.
Upvotes: 3