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

2012/9/12

help

Stephon231 Stephon231

2012/9/12

#
what is the code to make a world get a method form an actor
Gevater_Tod4711 Gevater_Tod4711

2012/9/12

#
If the method you want to execute is static you just need this:
actorsName.methodsName();
If it is non-static (what it probably is) you first need the reference to the actor:
import java.util.List;

public class MyWorld extends World {
    
    Object obj;
    
    public void act() {// or any other method;
        List<object> o = getObjects(object.class); // object is the type of the object you want to have the reference to.
        if (o.size() != 0) {
            obj = o.get(0);//gives the reference to the first object in world that is found.
            obj.method(); //the method you want to execute.
        }
    }
}
If you need another object (not the first what is found) you have to serch for this. maybe with an int type or something like this.
Stephon231 Stephon231

2012/9/12

#
would this be correct: <Wombat> o = getObjects(Wombat.class); // if (o.size() != 0) { obj = o.get(0); obj.method(leavesE); }
danpost danpost

2012/9/13

#
@Gevater_Tod4711, it is probably best to avoid the List class when dealing with those that are just starting off. It adds an extra layer of complexity. Easier would be:
if (!getObjects(Wombat.class).isEmpty()) ((Wombat) getObjects(Wombat.class).get(0)).method();
However, it would probably be even better to have a reference to the Wombat in an instance field in the world.
// world instance variable
Wombat wombat = null;
// in the constructor (or a method it calls)
wombat = new Wombat();
addObject(wombat, xxx, yyy);
// then, to call the method later
wombat.method();
Of course 'xxx' and 'yyy' should be replaced either with actual values, pre-set variables or legal expressions. If you need to find out if 'wombat' is still in the world first, you can use
if (wombat.getWorld() != null)
You need to login to post a reply.