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

2016/6/26

Actor not in world

Kelem Kelem

2016/6/26

#
Hi guys, First time posting here but I have received a lot of help from reading other posts. I'm working on a game and I keep getting an error when a spaceship is destroyed. I think it's because the spaceship is firing a laser and Greenfoot is trying to get the X and Y coordinates of the spaceship object but it can't because it has been destroyed. Here is the code for my fire method.
 /**
     * Fires a green laser.
     */
    public void fire()
    {
        if(gunTimer == 0)
        {
            getWorld().addObject(new ImperialLaser(getRotation()+180, -(velocity * 3), "greenlaser"), getX() - 1, getY() - 0);
            
            gunTimer = gunTimerMax;

            //Greenfoot.playSound(".wav");
        }
        else if(gunTimer > 0)
        {
            gunTimer--;
        }

    }
The error was:
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.
	at greenfoot.Actor.failIfNotInWorld(Actor.java:695)
	at greenfoot.Actor.getX(Actor.java:157)
	at TieIn.fire(TieIn.java:104)
	at TieIn.act(TieIn.java:36)
	at greenfoot.core.Simulation.actActor(Simulation.java:594)
	at greenfoot.core.Simulation.runOneLoop(Simulation.java:552)
	at greenfoot.core.Simulation.runContent(Simulation.java:215)
	at greenfoot.core.Simulation.run(Simulation.java:205)
In order to fix it I tried this....
 /**
     * Fires a green laser.
     */
    public void fire()
    {
        if(gunTimer == 0 && !getWorld().getObjects(TieIn.class).isEmpty())
        {
            getWorld().addObject(new ImperialLaser(getRotation()+180, -(velocity * 3), "greenlaser"), getX() - 1, getY() - 0);
            
            gunTimer = gunTimerMax;

            //Greenfoot.playSound(".wav");
        }
        else if(gunTimer > 0)
        {
            gunTimer--;
        }

    }
...but this just got me a Null pointer exception error. Any help appreciated and I'm happy to provide further info. Thanks!
danpost danpost

2016/6/26

#
I think you need to stick with your original code and post your act method of the class. You may also want to inform us of any method that has the following line in it:
getWorld().removeObject(this);
You may also want to show all codes that deals with the 'gunTimerMax' field.
You need to login to post a reply.