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

2016/3/21

Crashing when actor gets destroyed.

Lavuco Lavuco

2016/3/21

#
Hello, so my game is crashing when Enemy gets destroyed. The crash error i get is
java.lang.NullPointerException
	at Enemy.act(Enemy.java:22)
	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)
And here is the Enemy code:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Enemy here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Enemy extends Actor
{

    /**
     * Act - do whatever the Enemy wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {

        destroyEnemies();

        Hero hero = (Hero)getWorld().getObjects(Hero.class).get(0);
        turnTowards(hero.getX(), hero.getY());
    }

    public void destroyEnemies()
    {
        //"Enemy" can be any class that you want the bullet to destroy. 
        Actor Bullet = getOneObjectAtOffset(0, 0, Bullet.class);
        if (Bullet != null){ 
            getWorld().removeObject(Bullet);
            getWorld().removeObject(this);
        }
    }


}
Any ideas how to fix it ? :o I was trying to make this Enemy follow actor "Hero" which is controlled by the user.
Super_Hippo Super_Hippo

2016/3/21

#
As the comment in line 27 already suggests, the method should be in the bullet class. A bullet can destroy something, but it doesn't make sense that the method 'destroyEnemies' is in the Enemy class and actually it is not destroying Enemies. The enemy is destroying itself when touching a bullet. If you only want to eliminate the error, call the destroyEnemies-method at the end of the act-method instead of line 19.
Lavuco Lavuco

2016/3/21

#
It works hehe ty ^_^ Yeh the enemy is destroying itself when touching a bullet i found it more interesting to do hehe So yeh it works now and the thing i did wrong was calling it in the wrong place hehe
You need to login to post a reply.