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

2020/2/6

Isn't loading new background

kowordidi kowordidi

2020/2/6

#
This code is part of an actor from MyWorld:
if(isTouching(Pirate.class))
        {
            isGameOver = true;
            this.getWorld().removeObjects(getWorld().getObjects(Pirate.class));
            this.getWorld().removeObjects(getWorld().getObjects(Treasure.class));
            this.getWorld().removeObjects(getWorld().getObjects(Ship.class));
            ((MyWorld)this.getWorld()).setBackground("Loosescreen.png");
        }
All of the Objects are removed, so the if statement is run. The filename is correct (I checked like 10 times) but I get an error message every time: java.lang.NullPointerException at Ship.act(Ship.java:80) at greenfoot.core.Simulation.actActor(Simulation.java:604) at greenfoot.core.Simulation.runOneLoop(Simulation.java:562) at greenfoot.core.Simulation.runContent(Simulation.java:221) at greenfoot.core.Simulation.run(Simulation.java:211) it also worked when I changed the image directly from the constructor of MyWorld. Do any of you know what I might be doing wrong? Thanks in advance
Super_Hippo Super_Hippo

2020/2/6

#
Move line 7 to before line 4 (or at least before line 6). So set the background before you remove the actors. The actor which is executing the code (the ship) is removed from the world in line 6. After that, you can’t try to set the background of the world which is returned by getWorld() because that is null (the object isn’t in any world since you just removed it from the world). Alternatively, you can get the reference to the world before removing it:
World w = getWorld();
w.removeObjects(w.getObjects(Pirate.class));
w.removeObjects(w.getObjects(Treasure.class));
w.removeObjects(w.getObjects(Ship.class));
w.setBackground("Loosescreen.png"); //you might want to remove one “o” in the file name
You need to login to post a reply.