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

2015/8/27

I get a null error

WarRaven WarRaven

2015/8/27

#
when i try to run this it gives me a NullPointerException
public class HealthBar extends Actor{
    public byte lives  = ((Unit)getWorld().getObjects(Unit.class).get(0)).lives;;
    private byte healthBarWidth = 60;
    private byte healthBarHight = 6;
    private byte LengthPerHealth = (byte)(healthBarWidth/lives);



    public void act(){
        update();
    } 

    /**
     * This is were we create the method of selecting a unit
     */
    public void update(){
            setImage(new GreenfootImage(healthBarWidth + 2, healthBarHight + 2));
            GreenfootImage healthImage = getImage();
            healthImage.setColor(Color.WHITE);
            healthImage.drawRect(0, 0, healthBarWidth + 1, healthBarHight + 1);
            healthImage.setColor(Color.BLUE);
            healthImage.fillRect(1, 1, healthBarWidth + 1, healthBarHight + 1);
    }

    public void hit(){
        lives --;
    }
}
import greenfoot.*; /** * Write a description of class Unit here. * * @author (your name) * @version (a version number or a date) */ public class Unit extends Actor{ boolean Selected = false; public byte lives = 6; /** * * Act - do whatever the Unit wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { healthBar(); } public void healthBar(){ int x = getX(); int y = getY() - 35; getWorld().addObject( new HealthBar() , x , y); } }
danpost danpost

2015/8/27

#
You cannot use 'getWorld' in the constructor of the Actor subclass. The object must be created (or, the constructor is executed) prior to the actor ever being placed into a world. So, 'getWorld' will return a 'null' value at that time. There are several ways to retrieve the value of the 'lives' field of the Unit object (or maybe you can just set the value of the 'lives' field of the HealthBar object to the appropriate value literally ('public byte lives = 5;', for example). If you must get the value directly from the Unit object, then you can do so in the 'addedToWorld' method. Like the 'act' method, it is called automatically by greenfoot, but when an actor is added into a world. It is overridden in the same way:
public void addedToWorld(World world)
{
    lives = ((Unit)world.getObjects(Unit.class).get(0)).lives;
}
You still need to declare the lives field, so:
public byte lives;
should suffice.
You need to login to post a reply.