I am currently working on a game where I want to have a timer for the remaining time. The actual variable for the timer is in the world "MyWorld", so the timer should only display the remaining time. When I compiled my game there was no error, but when I tried to start it I've got the following error:
java.lang.NullPointerException
at Timer.<init>(Timer.java:14)
at Level0.prepare(Level0.java:38)
at Level0.<init>(Level0.java:20)
This is the code of MyWorld:
And this of the Actor Timer:
Can anybody help me, please?
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class MyWorld here. * * @author (your name) * @version (a version number or a date) */ public class MyWorld extends World { long time = 50; long absoluteTime = 160; GreenfootSound music = new GreenfootSound("571236_Load.mp3"); /** * Constructor for objects of class MyWorld. * */ public MyWorld(Player player, int xPos, int yPos) { super(896, 448, 1); this.addObject(player,xPos,yPos); Greenfoot.setSpeed(62); if (time <= 0) { music.stop(); } } public void act() { time--; Greenfoot.delay(380); } public void started() { music.play(); } public void stopped() { music.pause(); } public long getTime() { return time; } }
import greenfoot.*; import java.awt.Color; import java.util.List; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Timer here. * * @author (your name) * @version (a version number or a date) */ public class Timer extends Actor { MyWorld myworld = (MyWorld) getWorld(); long timer = myworld.time; public Timer() { GreenfootImage img = new GreenfootImage("Time remaining: " +timer, 35, Color.white, new Color(0, 0, 0, 0)); setImage(img); } /** * Act - do whatever the Timer wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. GreenfootImage img = new GreenfootImage("Time remaining: " +timer, 35, Color.white, new Color(0, 0, 0, 0)); setImage(img); } }