When my enemy gets to the bottom of the screen I want to remove and if the enemy gets hit by bullets i want to remove it. The error is : 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.
I think the problem is because there is two calls to removeObject or the getOneIntersectingObject method is causing an error. How do I fix this?
This is the code causing the error
public class Enemy extends Actor
{
public void act()
{
setLocation(getX(), getY() + 3);
if (getY() > getWorld().getHeight() + 30 )
getWorld().removeObject(this);
Actor fire = getOneIntersectingObject(Fire.class);
if(fire != null)
getWorld().removeObject(this);
}
}
Greenfoot doesn't allow any interactions with the world after an actor has been removed from it. If your Y coordinate causes this
actor to be removed from the world in the first if statement, it is an error to call getOneIntersectingObject
afterwards.
There's several ways to solve this: you could wrap the ensuing lines in an else
clause, you could make an early return
if you remove yourself in the first if, or you could use a boolean
flag to keep track of whether you want to remove yourself, but only do the removal as the very last item in the act()
method.