Reputation: 35
Hello and thank you for reading this. I am coding in java/LWJGL. My problem is that I keep getting a null pointer error with some code if I don't include this one thing. Basically there are 4 classes
The boot class creates a display and in the game loop it runs the draw method that is inside the blockgrid class. To set where a block goes i would use the renderat(x,y) method inside the blockgrid method. The block class just creates a quad at a certain x,y.
Sorry if I'm not explaining good. Here is my code: This is where the error happens just read my comments to see where the error is.
// BlockGrid.java
package minecraft2d;
import java.io.File;
public class BlockGrid {
private Block[][] blocks = new Block[100][100];
public BlockGrid() {
for (int x = 0; x < 25 - 1; x++) {
for (int y = 0; y < 16 - 1; y++) {
blocks[x][y] = new Block(BlockType.AIR, -100, -100); //This is where my error happens! If I don't include this line i get a null pointer. Anything will help. I am really stuck and don't know whats happening
}
}
}
public void setAt(int x, int y, BlockType b) {
blocks[x][y] = new Block(b, x * 32, y * 32);
}
public void draw() {
for (int x = 0; x < 25 - 1; x++) {
for (int y = 0; y < 16 - 1; y++) {
blocks[x][y].draw();
}
}
}
}
Upvotes: 0
Views: 501
Reputation: 7403
The reason you get a NullPointerException when you don't have that line is that blocks[x][y] will be null
for all x,y when draw() is called. draw() assumes you have valid Block objects because it's calling Block#draw.
Upvotes: 2