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

2020/10/8

How can I access Methods from a subclass of World in an Actor class?

Dev_grey97 Dev_grey97

2020/10/8

#
public class MyWorld extends World {  

public GreenfootSound backgroundMusic = new GreenfootSound("crab_wave.mp3");

}

public class MyActor extends Actor {

   private MyWorld myWorld  = (MyWorld) getWorld();

    public void foo(){
           myWorld.backgroundMusic.playLoop();
    }
}

When I start the program and call the function foo() I recieve the following Exception: java.lang.NullPointerException Any Ideas how I can fix my code?
danpost danpost

2020/10/8

#
Your MyActor actor is not in any world when it is being created -- and when the field myWorld is assigned its value. Use the following to assign its value:
protected void addedToWorld(World world)
{
    myWorld = world;
}
Greenfoot internally calls this (override) method once each time an actor is placed into a world (see Actor class API documentation).
Dev_grey97 Dev_grey97

2020/10/8

#
danpost wrote...
Your MyActor actor is not in any world when it is being created -- and when the field myWorld is assigned its value. Use the following to assign its value:
protected void addedToWorld(World world)
{
    myWorld = world;
}
Greenfoot internally calls this (override) method once each time an actor is placed into a world (see Actor class API documentation).
Thanks for the quick answer but could you please elaborate how I can add the actor to the world and how to use the method addedToWorld() ?
danpost danpost

2020/10/8

#
Dev_grey97 wrote...
could you please elaborate how I can add the actor to the world and how to use the method addedToWorld() ?
Show entire page of MyWorld class codes. Oh, line 3 above, given by me, is flawed. It should be:
myWorld = (MyWorld) world;
You need to login to post a reply.