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

2016/3/11

How to get Actor that is not in the world to stop running code

Hydrowarrior Hydrowarrior

2016/3/11

#
I know what the problem is, the cars keep trying to run the code but they are not in the world so it returns an error, but I do not know how to fix it. Could somebody help me?
public class Vehicle extends Actor
{
    private int Speed = Greenfoot.getRandomNumber(5)+3;
    public void act() 
    {             
        vehicleMove();
        collide();
        bottomOfScreen();
    }    

    public void bottomOfScreen()
    {
        if(getY()>= getWorld().getHeight()-1){getWorld().removeObject(this);}
        return;
    }

    public void collide()
    {
        Actor collided;
        collided = getOneIntersectingObject(Vehicle.class);
        if (collided != null){Greenfoot.playSound("Explosion.wav");getWorld().removeObject(this);}
        return;
    }

    public void vehicleMove()
    {      
        setLocation(getX(),getY()+Speed);
    }
}
danpost danpost

2016/3/11

#
Okay -- you have two methods, 'collide' and 'bottomOfScreen', that each require that the actor be in a world (and each which could remove the object from any world it might be in). A sure fix would be to add the following line as the first line in both methods:
if (getWorld() == null) return;
By the way, line 22 is not needed as there is no code that needs to be avoided after it (the method ends there and execution will return, anyway).
You need to login to post a reply.