Hello,
I keep getting this java.lang.NullPointerException error everytime I am trying to move my hero in a portal to switch the worlds. I really have no clue what to do. Help would be appreciated.
Thats the error:
Line 24 in Overworld is:
Line 39 in Portal is:
And Line 25 in Portal is:
My Code:
java.lang.NullPointerException at Overworld.getWorld(Overworld.java:24) at Portal.switchWorld(Portal.java:39) at Portal.act(Portal.java:25)
for (World world : worlds) {World newWorld = Overworld.getWorld(worldClass);
switchWorld(hero);
public class Overworld extends World
{
public static ArrayList<World> worlds;
public Overworld()
{
super(600, 400, 1);
worlds = new ArrayList<World>();
worlds.add(new Level1());
worlds.add(new Level2());
Greenfoot.setWorld(worlds.get(0));
}
public static World getWorld(Class worldClass)
{
for (World world : worlds) {
if (world.getClass() == worldClass) {
return world;
}
}
return null;
}
}
public class Portal extends Actor
{
Class worldClass;
int x;
int y;
public Portal(Class worldClass, int x, int y)
{
this.worldClass = worldClass;
this.x = x;
this.y = y;
}
public void act()
{
Hero hero = (Hero) getOneIntersectingObject(Hero.class);
if (hero != null) {
switchWorld(hero);
}
}
private void switchWorld(Hero hero)
{
int invX;
int invY;
invX = hero.getInventory().getX();
invY = hero.getInventory().getY();
World oldWorld = getWorld();
oldWorld.removeObject(hero.getInventory());
oldWorld.removeObject(hero);
World newWorld = Overworld.getWorld(worldClass);
newWorld.addObject(hero.getInventory(), invX, invY);
newWorld.addObject(hero, x, y);
Greenfoot.setWorld(newWorld);
}
}

