This site requires JavaScript, please enable it in your browser!
Greenfoot back
Asiantree
Asiantree wrote ...

2017/3/3

Help with NullPointerException Error

Asiantree Asiantree

2017/3/3

#
//this is inside my player class, I am trying to remove a player when he touches a bomb and then decrease life count and then add another player }
public void die () 
    {
        int lifeCount = 3;
        BouncingBomb b = (BouncingBomb) getOneIntersectingObject(BouncingBomb.class);
        if (b != null)
        {
            World w = getWorld();
            MyWorld mw = (MyWorld) getWorld();
            Player play = mw.getPlayer();
            getWorld().removeObject(play);
            lifeCount-- ;
            if (lifeCount == 2)
            {
                getWorld().addObject(new Player(), 20, 545);
            }
            if (lifeCount == 0) 
            {
                dead = true;
            }
        }
    }
Super_Hippo Super_Hippo

2017/3/3

#
The reason why it is not working is that line 10 removes the object from the world and then in line 14, you are trying to add an object to a not existing world. You don't need to get a reference to the player from the world. You can simply use 'this'. However, when adding a new player, this player will have 3 life again. So maybe you can just teleport it to the start again. Test the following:
private int lifeCount = 3; //outside methods!

public void die() //seems to be a misleading name by the way
{
    if (isTouching(BouncingBomb.class))
    {
        lifeCount--;
        if (lifeCount == 0) dead = true;
        else setLocation(20, 545);
    }
}
You need to login to post a reply.