Hey guys,
I am getting an occasional null pointer exception in my games ObjectManager class. I can’t seem to find a pattern as to why this is happening and could use some help. Every object in my game is added and removed by this ObjectManager class by checking the objects alive property. This property is set in collision methods when two objects collide so that the ObjectManager knows when to remove them.
Below is the ObjectManager update method:
public void update()
{
GameObject a, b;
// Update the objects and cull the dead
for(int i=0; i<objects.size(); i++)
{
objects.get(i).update();
if(objects.get(i).isAlive() == false)
{
objects.get(i).destroy();
objects.remove(i);
}
}
// Check for collision
for(int i=0; i<objects.size(); i++)
{
for(int j=i; j<objects.size(); ++j)
{
a = objects.get(i);
b = objects.get(j);
if(a == b) continue;
// Finally do the test and alert both objects
if(collision(a,b))
{
a.collision(b);
b.collision(a);
}
}
}
}
Here is my relevant stack trace:
Exception in thread "Thread-3" java.lang.NullPointerException
at shooter.engine.ObjectManager.collision(ObjectManager.java:110)
at shooter.engine.ObjectManager.update(ObjectManager.java:83)
at shooter.game.PlayScreen.update(PlayScreen.java:33)
at shooter.engine.ScreenManager.update(ScreenManager.java:15)
at shooter.engine.GamePanel.update(GamePanel.java:137)
at shooter.engine.GamePanel.run(GamePanel.java:127)
at java.lang.Thread.run(Unknown Source)
Here is the collision method from the stack trace:
private boolean collision(GameObject a, GameObject b)
{
double dx = a.getX() - b.getX();
double dy = a.getY() - b.getY();
double dist = Math.sqrt(dx * dx + dy * dy);
if(dist < a.getR() + b.getR()) return true;
return false;
}
The line that it’s pointing to is in the collision method. I don’t see how it could be null because “dead” objects are removed before checking for collision. The crash doesn’t always occur in the collision method, sometimes it occurs in the update method posted above. Any ideas? I would be happy to post more code if needed.