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

2014/11/25

NullPointerException error

Anonymous2014 Anonymous2014

2014/11/25

#
I'm making a 2D maze game and attempting to open a portal to a second level once 5 items have been collected from the maze. The portal to the next level works fine I just need to add it into the world after all 5 items have been collected. This is what I have so far:
public class SpaceshipPart extends Actor
{
    public static int spaceshipPart = 0;
    /**
     * Act - do whatever the SpaceshipPart wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        collectParts();
    }    

    public void collectParts()
    {
        Actor d = getOneIntersectingObject(Spaceman.class);
        if (d != null)
        {
            World MazeWorld = getWorld();
            MazeWorld.removeObject(this);
            spaceshipPart++;
        }
        if(spaceshipPart == 5)
        {
            getWorld().addObject(new LEVEL1(), 986, 584);
        }
    }
}
This gives me a nullPointerExceptionError and I can't figure out why. Any help would be great! Cheers.
danpost danpost

2014/11/26

#
If this line (or something very close to it) is showing up in your terminal error message:
at SpaceshipPart.collectParts(SpaceshipPart.java:26)
then the NullPointerException is thrown because 'getWorld' on line 24 (above) is returning a 'null' value, in turn, because the actor intersected a Spaceman object and line 19 (above) removed the actor from the world. I am presuming that the Spaceman object must collect the 5 SpaceshipPart objects here. The biggest problem with your code is that the int field 'spaceshipPart' will never be more than one for any SpaceshipPart object. Each object has its own field to increment and removing the object loses the field for that object. In other words, that field and its accompanying code (which seems to pretty much be all the code in the SpaceshipPart class) should be elsewhere, either in the Spaceman class or the MazeWorld class. The Spaceman class would seem to be the better place since it is the object of that class that does the collecting.
Anonymous2014 Anonymous2014

2014/11/27

#
Thanks! Think I've got it working now. Thanks for the help :)
You need to login to post a reply.