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

2018/9/8

Accesing a variable or method of a world subclass

HandsomeDodge HandsomeDodge

2018/9/8

#
Hey guys, i have a problem accesing a value out of a world subclass from my actor subclass because im getting a nullpointer exception. I can get a value directly from the world subclass aka. System.out.println(s2); so that means it should not be null. My actor class:
Projectile(){
        
     AntWorld antWorld = (AntWorld) getWorld();
      System.out.println(antWorld.getS2());
}
My world class:
    public int getS2() {
    int s2 = getObjects(S2.class).size();
       System.out.println(s2);
       return s2;
    }
What do i do wrong? Thx in advance!
Asenoju Asenoju

2018/9/8

#
The problem is that you wrote the "getWorld()" method right into the constructor. It's like that: First, the object is "built" (aka the constructer is called) and AFTER the object has been "built", it's added into the world. That means, by the time you call "getWorld()" there is no world your projectile is in. I suggest you to look into the "addedToWorld(World world)" method. That method is called right after an Actor has been added to the world, so you could use getWorld() in there instead of the constructor. This should fix your problem ;) Happy programming!
HandsomeDodge HandsomeDodge

2018/9/9

#
Asenoju wrote...
The problem is that you wrote the "getWorld()" method right into the constructor. It's like that: First, the object is "built" (aka the constructer is called) and AFTER the object has been "built", it's added into the world. That means, by the time you call "getWorld()" there is no world your projectile is in. I suggest you to look into the "addedToWorld(World world)" method. That method is called right after an Actor has been added to the world, so you could use getWorld() in there instead of the constructor. This should fix your problem ;) Happy programming!
It worked! Thank you!
Asenoju Asenoju

2018/9/9

#
HandsomeDodge wrote...
Asenoju wrote...
The problem is that you wrote the "getWorld()" method right into the constructor. It's like that: First, the object is "built" (aka the constructer is called) and AFTER the object has been "built", it's added into the world. That means, by the time you call "getWorld()" there is no world your projectile is in. I suggest you to look into the "addedToWorld(World world)" method. That method is called right after an Actor has been added to the world, so you could use getWorld() in there instead of the constructor. This should fix your problem ;) Happy programming!
It worked! Thank you!
No problem! ;)
You need to login to post a reply.