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

2018/5/20

Remove Objects

codecodecode codecodecode

2018/5/20

#
Hello, I am currently coding a program where obstacles periodically appear and cross a map. However, I want these obstacles to disappear one by one once they reach the map edge. But when I put in the code for this, I get a NullPointerException after about three objects are spawned. Can anyone help me? Thank you! public void act() { slide(); spawn(); } public void slide() { if (!(getX()==0)) { setLocation(getX()-3, getY()); } else { Actor ob = getOneObjectAtOffset(0, 0, Obstacle1.class); getWorld().removeObject(ob); getWorld().removeObject(this); } } public void spawn() { spawnCounter++; if (spawnCounter == 200) { spawnCounter = 0; getWorld().addObject(new Obstacle1(), 780, 470); } }
jamesN616 jamesN616

2018/5/21

#
Try amending the code so that ob is only removed if it exists:
else
{
    Actor ob = getOneObjectAtOffset(0,0, Obstacle1.class);
    if(ob != null)
    {
        getWorld().removeObject(ob);
    }
    getWorld().removeObject(this);
}
danpost danpost

2018/5/21

#
You were probably getting the error when the first one reached the left edge of the world (and after a small number of them were spawned behind it). The fix suggested by jamesN616 will probably stop the error from happening. More simply might be this:
else
{
    removeTouching(Obstacle1.class);
    getWorld().removeObject(this);
}
However, don't you have more issues here? like non-removal while collisions are occurring while crossing the map? or, sometimes too many objects being spawned and sometimes spawning ceases to occur?
You need to login to post a reply.