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

2018/7/23

Calling Methods

SevenGrnSix SevenGrnSix

2018/7/23

#
When I call a method between two actor classes, it never seems to work. But, if I call it from the World subclass using getWorld it works. I call it like I am making an instance, but, that seems to be the problem. Anyone know of or have an example of calling a method from another subclass of the Actor Class?
Super_Hippo Super_Hippo

2018/7/23

#
If you want to call a method on a specific object, you need a reference to that object. If an object calls a method on itself (for example 'move(2)', it automatically gets the reference to itself, 'this.move(2)'). If the execution of the method happens from a different object, this object needs to get a reference to that object. With 'getWorld()' you get a reference to the world in which the object currently is (if any) and you can call methods on that world object. To get a reference to a specific object in the world, you can (if there is only one instance of that class in the world), do:
1
Classname objectReference = (ClassName) getWorld().getObjects(ClassName.class).get(0);
If there are more than one instance of the class, you need to get the reference differently. Let's say you have a worker in a mine who collects ore. You have the classes 'Worker' and 'Mine' and the mine has a ore resource variable which should be decreased whenever the worker collects some. The worker on the other hand also wants to keep track how much ore he collected. The code could look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Worker
private int oreCollected=0, maxOre=10;
 
public void act()
{
    if (oreCollected < maxOre)
    {
        Mine mine = (Mine) getOneIntersectingObject(Mine.class);
        if (mine != null && !mine.isEmpty())
        {
            mine.removeOre();
            oreCollected++;
        }
    }
}
1
2
3
4
5
//Mine
private int ore = 100;
 
public boolean isEmpty() {return ore<1;} //only needed if empty mines are not removed from the world
public void removeOre() {ore--;}
SevenGrnSix SevenGrnSix

2018/7/23

#
Interesting, but I think it is something else than my question that is the problem. That is, I answered my own question, I think.
You need to login to post a reply.