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

2015/11/10

Accessing a variable from another class

6716070 6716070

2015/11/10

#
I have a variable called score in one of my classes (public int score;) I need to change this from a different class. I am trying this: score = score - 20; but it does not work. It says "cannot find symbol - variable score"
danpost danpost

2015/11/10

#
You cannot directly reference a field from another class. The 'score' field belongs to some object (maybe a World object -- maybe another Actor object) created from another class. As such, you need a reference to an object that has the field -- the specific object you want the value from. Let us say you have a world class named 'MyWorld' and a 'score' field is given to each World object created from the class. Then, from an Actor subclass, an object in a MyWorld world can use:
1
int worldScore = ((MyWorld)getWorld()).score;
or, more simply put:
1
2
3
World world = getWorld();
MyWorld myWorld = (MyWorld) world;
int worldScore = myWorld.score;
You need to login to post a reply.