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

2014/3/8

NullPointerException trying to access a variable from one class in another

polar568 polar568

2014/3/8

#
I am trying to access a health variable from my Tank.class and change it when the Tank gets hit with an Arrow. Here is the code:
public void hit()
    {
        Tank tank = (Tank)getOneIntersectingObject(Tank.class);
        if(getOneObjectAtOffset(0, 0, Tank.class) == tank) {
            tank.health = tank.health - 1;
            getWorld().removeObject(this);
        }
    }
It is on line 5 where the error is occurring. I did have it working by using getOneIntersectingObject in the if statement, but it was detecting a hit before it had actually hit the Tank since the image had empty space around the Tank. Thanks in advance!
danpost danpost

2014/3/8

#
Download my Image Transparency Adder/Trimmer scenario and run it. All you have to do is 'Load' and 'Save' the image and any excess transparency will be removed. Also, may need to see your tank class code to see how to access the 'health' field in it.
polar568 polar568

2014/3/8

#
The only place I have the health in the Tank class is outside of the methods but in the class with this:
public int health = 3;
I tried that image transparency tool and then switched the getOneObjectAtOffset to getOneIntersectingObject, but nothing happened when the arrows touched the tanks. I also tried this, but it didn't work either:
public void hit()
    {
        Tank tank = (Tank)getOneIntersectingObject(Tank.class);
        if(tank != null) {
            tank.health = tank.health - 1;
            getWorld().removeObject(this);
        }
    }
danpost danpost

2014/3/8

#
The code in your last post seems to be alright. Maybe the problem resides elsewhere. After an arrow hits a tank, did you try stopping the scenario, right-clicking on the tank and select 'Inspect' to see if the 'health' value actual decreased or not? What do you mean by 'nothing happened when the arrows touched the tanks'? are the arrows passing right through the tanks? or are the arrows disappearing?
Pointifix Pointifix

2014/3/8

#
oh those lines, i hate them ;)
tank.health = tank.health - 1;
you could use the most beautiful solution :)
tank.health--;
or for greater numbers:
tank.health-=value;
polar568 polar568

2014/3/8

#
You're right, I made a stupid mistake and left out hit() from the act method. Anyway thanks for the health subtracting tip!!! All these problems are solved now!
You need to login to post a reply.