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

2013/1/25

Having a problem creating an object.. from an object.

Minion1 Minion1

2013/1/25

#
Ok, here's the flowdown: Cursor moves around for a bit, then makes a call to start a battle. It uses this code:
public void beginBattle()
    {
        getWorld().addObject(new Battle(), 349, 128);
    }
That makes a call to create a "Battle" object. The battle class is then called, and does this:
public class Battle extends Actor
{
    private BattleBackdrop enemyField;
    
    public Battle()
    {
        //Creates a battle screen and places it.
        //enemyField = getWorld().addObject(new enemyField, 349, 128);
        enemyField = new BattleBackdrop();
        getWorld().addObject(enemyField, 349, 128); //null pointer right here.

        //Calls the method setEnemies() to set enemies on the battle backdrop.
        setEnemies();        
    }
At which point, there is a null pointer exception where indicated above. I've been racking my brain and tracing the code, but for the life of me I can't tell why the battle class can't create this object:
public class BattleBackdrop extends Backdrops
{
    private GreenfootImage img = new GreenfootImage("Battlescreen2.png");
    
    public BattleBackdrop()
    {
        setImage(img);
    }
Can anyone help? I'm trying to create a turn based battle system, and since no one knows how to do that, I'm on my own.
Minion1 Minion1

2013/1/25

#
I suspect that I'm somehow setting two objects in the same place (at 349, 128) and this is confusing the machine. I'm trying to start up a battle screen.
danpost danpost

2013/1/25

#
It is not that at all. What you are doing is trying to add a BattleBackdrop object into a world from which the Battle object, which you are creating it in, is still being constructed and not yet in any world. So there is no world returned from 'getWorld' to add the object in; hence the nullPointerException ('getWorld' returns null). What you can do is override the 'addedToWorld(World)' method, which is called when the object is added into the world, to create and add the objects.
public void addedToWorld(World world)
{
    enemyField = new BattleBackdrop();
    world.addObject(enemyField, 349, 128);
    setEnemies();
}
Which would leave you with an empty constructor.
Minion1 Minion1

2013/1/25

#
Ah, thank you.
You need to login to post a reply.