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

2014/7/26

gaining access to a public variable

davemib123 davemib123

2014/7/26

#
How do I gain access to a public variable? My Hero class has:
public int speed = 4;
How would i go about accessing this value from another class?
danpost danpost

2014/7/26

#
You would need a reference to your Hero object. It is the Hero objects that each hold a 'speed' field which has independent values. The class itself does not have a 'speed' field; it only has a line declaring that each object created from that class will be given a 'speed' field. If you only have one Hero (which is probably the case), then the following lines will get that reference:
// from world class
Hero hero = null; // variable to hold the Hero object (if any)
// can only get first element from list if there is a first element, so
if (!getObjects(Hero.class).isEmpty())
{
    hero = (Hero)getObjects(Hero.class).get(0); // setting the variable
}
if (hero != null) // was field set to a Hero object
{
    int speedValue = hero.speed; // getting your 'speed' value
    // code dealing with speed
}
from an actor class (with the actor in the world), use 'getWorld().getObjects(Hero.class)' (getting a reference to the World object to call the World member 'getObjects' on).
davemib123 davemib123

2014/7/26

#
ace. thanks for quick reply danpost :)
danpost danpost

2014/7/26

#
Looking into your TileSet trees class from your other discussion thread.
You need to login to post a reply.