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

2017/1/26

NullPointerException

AttilaNagy AttilaNagy

2017/1/26

#
Hello I'm trying to program a game but i get this error massage: java.lang.NullPointerException at Guard.<init>(Guard.java:23) Can somebody help me? I have a world (Level01), Hero class and few other Actor class (Guard,Heart...etc). I would like to change the variables of Hero from other Actors. Level01:
public class Level01 extends World
{
    public Hero goblin = new Hero();
    public TopDisplay TD;
    public BottomDisplay BD = new BottomDisplay();
    
    public Level01()
    {    
        super(800, 600, 1);
        TD = new TopDisplay();
        addObject(goblin,100,100);
        addObject(TD,getWidth()/2,20);
        addObject(BD,getWidth()/2,getHeight()-20);
        
        for (int i=0; i<6; i++)
        {
            addObject(new Barrel(), Greenfoot.getRandomNumber(750)+50, Greenfoot.getRandomNumber(300)+60);
            addObject(new Wall(), Greenfoot.getRandomNumber(750)+50, Greenfoot.getRandomNumber(300)+60);
            addObject(new Heart(), Greenfoot.getRandomNumber(800), Greenfoot.getRandomNumber(300)+50);
        }
        
    }
    public Hero getHero()
    {
        return goblin;
    }
}
Hero:
public class Hero extends Actor
{
    //Variable of hero's properties
    int maxHP=100;
    int HP=100;
    int maxArmor=100;
    int armor=50;
public void changeHeroHP(int dHP)
    {
        if (HP+dHP>maxHP) HP=maxHP;
        else if ((HP+dHP)<1) {HP=0; gameOver();}
        else HP=HP+dHP;
    }
    public void gameOver()
    {
        Greenfoot.stop();
        
    }
}
Guard:
public class Guard extends Enemies
{
    Level01 w;
    Hero goblin;
    int speed=2;
    /**
     * 
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public Guard()
    {
        w=(Level01) getWorld();
        //goblin = (Hero) w.getObjects(Hero.class).get(0);
        goblin = w.getHero();
    }
    
    public void act() 
    {
        int x=getX();
        int y=getY();
        int gx=goblin.getX();
        int gy=goblin.getY();
        if (Math.abs(gx-x)>Math.abs(gy-y)){setLocation(x+speed*(Math.abs(gx-x)/(gx-x)),y);}
        else {setLocation(x,y+speed*(Math.abs(gy-y)/(gy-y)));}

        if (isTouching(Hero.class)) {goblin.changeHeroHP(-30);getWorld().removeObject(this);}
    }    
}
Super_Hippo Super_Hippo

2017/1/26

#
The constructor ('public Guard()...') is executed before the object is added to the world. Therefore, 'getWorld' returns null and you can't get the Hero object. You could use the addedToWorld method: (Make sure the Hero is added first.)
protected void addedToWorld(World world)
{
    Level01 w = (Level01) world;
    goblin = w.getHero();
}
As an alternative, you could also do it in the act method:
if (goblin == null)
{
    goblin = ((Level01) getWorld()).getHero();
}
//rest of act method
You need to login to post a reply.