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

2018/8/21

Null Pointer exception

adao3 adao3

2018/8/21

#
Hello guys, I am very new to coding and i am very confused with what i have to do to fix the issue. Any solution? this is the code for my bullet:
public class Bullet extends Actor
{
    /**
     * Act - do whatever the Bullet wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    
    public Bullet(){
        
    }
    public void act() 
    {
        move(10);
        if (isAtEdge())
        getWorld().removeObject(this);
        killenemy();
    }    
    public void killenemy(){
        if(isTouching(Enemy.class)){
        Actor Enemy = getOneIntersectingObject(Enemy.class);
        getWorld().removeObject(this);
        getWorld().removeObject(Enemy);
    }
}
}
This code is for my Enemy:
public class Enemy extends Actor
{
    /**
     * Act - do whatever the Enemy wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        followPlayer();
        
    }    
    public void followPlayer(){
if ( ! getObjectsInRange( 300, player.class ).isEmpty() )
{
    Actor player = getObjectsInRange( 300, player.class ).get( 0 );
    turnTowards( player.getX(), player.getY() );
    move(3);
}
    }
    
}
Super_Hippo Super_Hippo

2018/8/22

#
You could change your act-method to either this:
move(10);
if (isAtEdge())
{
    getWorld().removeObject(this);
    return;
}
killenemy();
or this:
move(10);
if (isAtEdge())
{
    getWorld().removeObject(this);
}
else
{
    killenemy();
}
The error happens because you are trying to call a method "getWorld" when the object is not in the world. "getWorld" returns "null" and you can't call methods on "null".
adao3 adao3

2018/8/22

#
hey, thanks for the fast response. I tried putting this in the act for my Bullet code but I still seem to get the error. I dont really know what the error is because i cant open the terminal. also can you explain to me what null means if possible, i am not really sure.
Super_Hippo Super_Hippo

2018/8/22

#
Oh you also have to swap lines 21 and 22 in Bullet. null basically means "no object".
adao3 adao3

2018/8/23

#
thank you that helped a ton
You need to login to post a reply.