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

2014/12/20

Null pointer exception

Dillybar Dillybar

2014/12/20

#
I am having an issue with the creation of an object in that when I attempt to add it to the world, I get this error:
java.lang.NullPointerException
	at FriendlyBullet.<init>(FriendlyBullet.java:17)
	at MarioG.shoot(MarioG.java:236)
	at MarioG.moveMario(MarioG.java:125)
	at MarioG.act(MarioG.java:52)
	at greenfoot.core.Simulation.actActor(Simulation.java:568)
	at greenfoot.core.Simulation.runOneLoop(Simulation.java:526)
	at greenfoot.core.Simulation.runContent(Simulation.java:215)
	at greenfoot.core.Simulation.run(Simulation.java:205)
Here is where how it is created:
public boolean bLeft = false;
    
    public FriendlyBullet()
    {
        MyWorld myWorld = (MyWorld)getWorld();
        bLeft = myWorld.marioL;
    }
There was no issue with this until I attempted to add in the left variable.
danpost danpost

2014/12/20

#
The 'public FriendlyBullet' block is the constructor for the object. This is executed when the 'new' keyword is used on the class name. Therefore, it is executed prior to its addition into the world. Using 'getWorld' will always return 'null' in the constructor of an Actor class. Anything that requires a world method or field must be done by overriding the 'addedToWorld' method which the greenfoot framework calls when the actor is added to the world (or by passing the world, or field value, to the constructor as a parameter).
Dillybar Dillybar

2014/12/20

#
ok, how is that done? here is where I add in the bullet:
public void shoot()
    {
        MyWorld myWorld = (MyWorld)getWorld();
        bullets = myWorld.getAmmo();
        if(reloadDelayCount >= gunReloadTime && bullets > 0)
        {
            ((SWorld)getWorld()).addObject(new FriendlyBullet(),getX(), getY(), false);
            reloadDelayCount = 0;
            myWorld.decreaseAmmunition();
        }
    }
Thnaks for your help :)
danpost danpost

2014/12/20

#
You can replace line 7 with the following:
MyWorld world = (MyWorld)getWorld();
FriendlyBullet fb = new FriendlyBullet();
fb.bLeft = world.marioL;
world.addObject(fb, getX(), getY(), false);
This was possible because both the 'bLeft' field and the 'marioL' field were made public.
You need to login to post a reply.