I'm new to using threads in general can someone explain why I sometimes get this exception:
Exception in thread "Thread-3" java.lang.NullPointerException
at Game.tick(Game.java:96)
at Game.run(Game.java:73)
at java.lang.Thread.run(Unknown Source)
It happens when the game starts or when I'm in the middle of playing. This error is so inconsistent as to when it decides to pop up, I have no idea what's causing it.
Here is the run and tick method:
public void run(){
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 100000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(isRunning) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1) {
tick();
//updates++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer += 1000;
frames = 0;
//updates = 0;
}
}
stop();
}
public void tick(){
for(int i = 0; i < handler.object.size(); i++){
if(handler.object.get(i).getId() ==ID.Player){
camera.tick(handler.object.get(0));
}
}
handler.tick();
}
My apologies if this post is very similar to other posts on threads I just need somewhat of a quick fix (if there is one). I'd forgot to mention that the error is different every time the game starts up for example:
Exception in thread "Thread-3" java.lang.NullPointerException
at Enemy.tick(Enemy.java:59)
at Handler.tick(Handler.java:13)
at Game.tick(Game.java:101)
at Game.run(Game.java:73)
at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-3" java.lang.NullPointerException
at Enemy.collision(Enemy.java:105)
at Enemy.tick(Enemy.java:31)
at Handler.tick(Handler.java:13)
at Game.tick(Game.java:101)
at Game.run(Game.java:73)
at java.lang.Thread.run(Unknown Source)
This is also this is the handler class if it helps:
import java.awt.Graphics;
import java.util.ArrayList;
public class Handler {
ArrayList<GameObject> object = new ArrayList<GameObject>();
public void tick(){
for(int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.tick();
}
}
public void render(Graphics g){
for(int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.render(g);
}
}
public void addObject(GameObject tempObject){
object.add(tempObject);
}
public void removeObject(GameObject tempObject){
object.remove(tempObject);
}
public void addObjectSpec(int i, GameObject tempObject){
object.add(i, tempObject);
}
}