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

2013/2/18

Null Pointer Errors

ajamesc97 ajamesc97

2013/2/18

#
Im using this code to remove an actor and create a new one once the first one is removed but i get a null pointer each time it is removed. What can i do to fix this?
public void create()  
    {   
        if(getX()==0)
        {
            getWorld().removeObject(this);
        }
        if(getWorld().getObjects(AlienBoss.class).isEmpty())  
        {  
            getWorld().addObject(new AlienBoss(),400,25);  
        }
    }  
danpost danpost

2013/2/18

#
Once you remove 'this' from the world, you lose the ability to use 'getWorld' to return the world it WAS in. The method returns 'null' instead. There are two ways to fix your code.
// the first way -- add before remove
public void create()
{
    if(getX()==0)
    {
        getWorld().addObject(new AlienBoss(),400,25);
        getWorld().removeObject(this);
    }
}

// the second way -- get a reference to the world while you can
public void create()
{
    if(getX()==0)
    {
        World world = getWorld();
        world.removeObject(this);
        world.addObject(new AlienBoss(),400,25);
    }
}
There is no sense in using two 'if' statements in this code. You know that when the one is removed that there are none in the world to add another. Just add another at that point when you remove one. Another possible solution is, as long as the AlienBoss object is not holding any values in fields that do not need reset to their initial state, is simply this:
public void create()
{
    if(getX()==0)
    {
         setLocation(400,25);
    }
}
Although, you could add code to reset any values at line 6 (for instance, to refresh the health or number of times hit).
ajamesc97 ajamesc97

2013/2/19

#
I was planning on adding time between the adding of the new AlienBoss, so the last one wouldn't work, and the first two gave me this error.
java.lang.IllegalStateException: Actor not in world. An attempt was made to use the actor's location while it is not in the world. Either it has not yet been inserted, or it has been removed
danpost danpost

2013/2/19

#
The first two ways should not be causing that error (maybe in something else you are doing, however). And any of the above ways will not add time between the adding of the new actor. You will need an int spawnTimer to control the duration of time waited to spawn the new actor.
You need to login to post a reply.