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

2017/11/23

Can't get access to counter in World subclass

Coolhand812 Coolhand812

2017/11/23

#
Hi everyone. I'm having a problem accessing a counter I created in a World subclass that keeps score in my game. I'm able to access it with the following code:
 this.getWorldOfType(Battleground.class).counter.add(5);
Unfortunately, this code ONLY works in this World and I have two more World subclasses, used as levels, to use. The entire method goes like this:
int enemyFighterDamage = 50;
    /**
     * fighterHit method is executed when a phaser hits an enemy fighter
     * in order to clear them from the battleground.
     * @param enemyFighterDamage adds five points of damage to the fighter
     *          until it reaches 50, when it is then removed from the world.
     */
    public void fighterHit()
    {
        enemyFighterDamage -= 5;
        this.getWorldOfType(Battleground.class).counter.add(5);
            //this.getWorldOfType(Battleground2.class).counter.add(5);
            //this.getWorldOfType(Battleground3.class).counter.add(5);
        removeTouching(Phaser.class);
        if(enemyFighterDamage < 5)
        {
            this.getWorld().removeObject(this);
        }
    }
I appreciate any help y'all can give me.
danpost danpost

2017/11/23

#
Coolhand812 wrote...
I'm having a problem accessing a counter I created in a World subclass that keeps score in my game. I'm able to access it with the following code:
 this.getWorldOfType(Battleground.class).counter.add(5);
Unfortunately, this code ONLY works in this World and I have two more World subclasses, used as levels, to use.
Do you have seperate counters in the other worlds? or, is the one counter to be used continuously throughout game play in all worlds?
Coolhand812 Coolhand812

2017/11/23

#
Yes, I have separate counters in the other worlds. Do you believe I need to have only one Score instance in the World superclass?
danpost danpost

2017/11/23

#
Coolhand812 wrote...
Yes, I have separate counters in the other worlds.
Then you can do something like this:
Counter counter = null;
if (getWorld() instanceof Battleground) counter = ((Battleground)getWorld()).counter;
else if (getWorld() instanceof Battleground2) counter = ((Battleground2)getWorld()).counter;
else if (getWorld() instanceof Battleground3) counter = ((Battleground3)getWorld()).counter;
if (counter != null) counter.add(5);
Coolhand812 Coolhand812

2017/11/23

#
Thanks, Danpost! Your're a life saver! Thanks!! I really appreciate your help!!
You need to login to post a reply.