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

2015/11/30

Getting a NullPointerException

oscarreks oscarreks

2015/11/30

#
So, in my Player actor, I have a "HEALTH" variable which draws it's value from the GameManager, which is a sub-class of World.
GameManager gm;
        
    public Player()
    {
        gm = (GameManager)getWorld();
        HEALTH = gm.playerHealth;
I initialize the empty GameManager reference. And then in the constructor, I set "gm" to point to the GameManager. And yet it keeps throwing NullPointerException, on the part where I set HEALTH equal to the playerHealth variable in the GameManager. And I'm sure I put the variables as public in GameManager. As far as I know, what I've put the references and stuff in the correct order. Yet the NPE is still thrown. Maybe the world doesn't exist until "Run" is clicked? I'm hoping there's an easy fix to this problem.
danpost danpost

2015/11/30

#
You are trying to get a world, using 'getWorld', in the constructor of the class. An actor cannot be in a world before its construction has completed. To be more specific: when you call 'new Player()', the constructor of the Player class executes; and this is done before any 'addObject' method can possibly add the actor into a world. Therefore, 'getWorld' will always return a 'null' value when used within the constructor. There are a couple of ways to set the value like you want. One way is to override the 'addedToWorld(World)' method which is called at the time the actor is placed into a world; however, this would limit the subtype of World the actor can be placed. The better way is to set it from the world from which the actor is created and added into:
Player player = new Player();
player.HEALTH = playerHealth;
addObject(player, < x >, < y >);
As an alternative, you could pass the value to the player when creating it:
// replace your line 3 through 6
public Player(int health)
{
    HEALTH = health;

// in world class, you would then use
Player player = new Player(playerHealth);
// or add a new player into the world with
addObject(new Player(playerHealth), < x >, < y >);
You need to login to post a reply.