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

2017/3/18

How to handle the act method, if there is no object

wueschn wueschn

2017/3/18

#
I have a problem with my little shooter, because I always get a null pointer exception with my code. It is the weapons class. This is a ball that "kills" an enemy and then disappears or it touches the edge which makes him disappear too. How can I avoid in the act method that it is not possibe to move() when there is no object... I guess this is the problem Here is the shown exception - 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. - Weapons.shooting(Weapons.java:35) - at Weapons.act(Weapons.java:20)
import greenfoot.*;  
public class Weapons extends Actor
{

    public Weapons()
    {
        GreenfootImage image = new GreenfootImage(20,20);
        Color color = new Color(255, 0,0);
        this.setImage(image);
        this.getImage().setColor(color);
        this.getImage().drawOval(0, 0, 20, 20);
        this.getImage().fillOval(0, 0, 20, 20);
        this.setRotation(270);

    }

    public void act() 
    {        
            this.move(10);
            this.shooting();
    } 

    public void shooting()
    {
        if(this.isTouching(Enemies.class))
        {
            Greenfoot.playSound("Explosion.wav");
            this.removeTouching(Enemies.class);
            this.getWorldOfType(MyWorld.class).getCounter().addScore();
            //delete the object
            this.getWorldOfType(MyWorld.class).removeObject(this);

        }

        if(this.isAtEdge())
        {
            //deletes the object
            this.getWorldOfType(MyWorld.class).removeObject(this);

        }

    }    
}
Thanks a lot for your help! wueschn
Super_Hippo Super_Hippo

2017/3/18

#
Just add an 'else' at the beginning of line 35.
wueschn wueschn

2017/3/18

#
Thanks a lot, works perfect! But I have to ask a question about the act method.
public void act() 
    {        
            this.move(10);
            this.shooting();
            this.doSomething();

    } 
If the method this.shooting() deletes the this-object, how does the act method react to the following this.doSomething() or the this.move(10) method, because there is no this object any more? Does it throw an Exception?
Super_Hippo Super_Hippo

2017/3/18

#
The object is not "deleted", it is only removed from the world. You can do anything with it after it was removed which does not require the object to be in a world.
You need to login to post a reply.