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

2019/3/29

What's wrong with this code?

EthanWasHere_ EthanWasHere_

2019/3/29

#
Ok so basically im getting the 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. With the code:
   
    public void image()
    {
        if (isTouching(Bee.class))
        {
           setImage("Explosion" + ".png");
           Greenfoot.delay(5);
           getWorld().removeObject(this);
        }
    }
    
    public void imageswap()
    {
        if (isTouching(Lizard.class))
        {
           setImage("Explosion" + ".png");
           Greenfoot.delay(5);
           getWorld().removeObject(this);
        }
    }
I get this error whenever the bee touches the trip_wire and it says the error is in the lizard part of this code but whenever the lizard touches the trip_wire it works perfectly fine, what am I doing wrong?
nccb nccb

2019/3/29

#
You cannot call methods which talk to the world after you've been removed from the world -- and this includes isTouching. So if one of these methods removes the actor from the world, you should not call the second method. One suggestion on how to fix this is to return a boolean from the method indicating if the actor was removed (like in this post). Another shorter check is to change:
if (isTouching(Lizard.class))
into:
if (getWorld() != null && isTouching(Lizard.class))
The check for the world not being null checks that you are still in the world, and thus should avoid the error in the case where the actor has been removed from the world.
You need to login to post a reply.