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

2014/3/10

Integer accessible in different actors

coderr coderr

2014/3/10

#
Hey guys, for part of my project i need to be able to access an integer and be able to edit from multiple different actors and different worlds. My first thought was to use a private int, but this didnt work. Any opinions? Thanks.
Game/maniac Game/maniac

2014/3/10

#
A private int wouldn't work, a better thing to do is use a public static int or give a reference to to class containing the integer in each actor you create. A static int is best for using as a constant variable, if the integer changes during the scenario you should use a reference to the class containing the integer.
polar568 polar568

2014/3/10

#
I just posted a question about this a few days ago. This might help you: http://www.greenfoot.org/topics/5720
danpost danpost

2014/3/10

#
What is the name you gave this int field, what is the name of the class you put it in, what type of class is it (World or Actor subclass), and what purpose did you have in mind for this field?
lordhershey lordhershey

2014/3/10

#
If it is a single int and it is being held in a unique instance I would do something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class ZZZ
{
private static int thatThingYouWant;
 
public void setThatThingYouWant(int val)
{
thatThingYouWant = val;
}
 
public int getThatThingYouWant()
{
return thatThingYouWant;
}
}
with it being a static member, you can read this value anywhere by: someint = ZZZ.getThatThingYouWant(); and you can set it by ZZZ.setThatThingYouWant(someint); This should be okay for straight forward linear processing.
danpost danpost

2014/3/10

#
The 'get' method proposed by lordhershey should also be declared 'static'
1
public static int getThatThingYouWant()
I am not saying that thing would be a viable solution for you situation; however, it may be. But be aware that the field, as 'static', must be initialized in your initial world constructor (or somehow else, if your create more than one instance of that world) or its value will be carried over between resets of the scenario.
lordhershey lordhershey

2014/3/10

#
I forgot to add this as well, you can make a static initialization block that is done only once when the class is loaded.
1
2
3
4
5
6
class ZZZ {
static int someVar;
 
/*here it is good for arrays and non changing images*/
someVar = 42;
}
But if you reset the game, this init block might not run again unless the class is dumped and reloaded into the JVM.
You need to login to post a reply.