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

2019/10/21

Bringing functions from another class

anonymous_panda anonymous_panda

2019/10/21

#
hi im trynna use a function defined in the class Level2 Level2 public int score = 0; public void increaseScore() { score++; } Fish public void act() { collectStarfish(); } public void collectStarfish(){ Actor Starfish; Starfish = getOneObjectAtOffset(0,0, Starfish.class); if (Starfish!=null){ World world; world = getWorld(); world.removeObject(Starfish); increaseScore(); } } doing this, it says that the method "increaseScore" cannot be found. how can i fix this? thanks
danpost danpost

2019/10/21

#
Using just:
increaseScore();
in your Fish class indicates that the method is either (1) in the Fish class; (2) in any one of its super classes (as a non-private method); or (3) in an interface that one of the aforementioned classes implements. Since it (the method) is located in your Level2 class, you need to indicate that that is where to find the method. Actually, it is the Level2 object (your current world object) that "has" the method. It is the score in that world that you want to increment. The getWorld() method will return a reference pointer to that world; however, the returned type is of World -- not Level2. That is, the method to be called must be on a Level2 type object -- not just a World type object. You can adjust the cast type by using (Level2)getWorld() so the method can be found:
((Level2)getWorld()).increaseScore();
You need to login to post a reply.