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

2012/5/3

Accessing a variable from the world class to create an object.

lgbrf lgbrf

2012/5/3

#
How do i access a variable (boolean) from a class and then use it to create an actor in world?
danpost danpost

2012/5/3

#
That would depend on what the boolean variable is used for. We would need to know 1) Are there ever any more that one object of that class, that the variable is in, in the world at one time? 2) If possible more than one, could both (or each) of them carry different values for that boolean, or is the variable more general to the class, than to the specific objects of that class? 3) Is(are) there a reference(s) to the object(s) of that class in the world class?
lgbrf lgbrf

2012/5/3

#
1) no there is only ever one of the object 2) no, because only one is ever required/can be made 3) what do you mean by references?
danpost danpost

2012/5/3

#
reference: a variable that holds the actor; but nevermind that. Since you only ever have one, you can make the boolean variable a 'static' one, making it a class variable instead of an instance variable. Then in the world class you can get the value by way of the class name. If your actor class was called 'Player' and the boolean variable was 'mutating', then in the world: if (Player.mutating) addObject(... Just by changing 'boolean mutating = false;' to 'static boolean mutating = false;'
danpost danpost

2012/5/3

#
I want you to keep in mind, however, that making the variable 'static' makes it a class variable; meaning that there is one, and only one, variable for that class (no matter how many objects you create in that class). This also means that the variable does NOT belong to any one object of that class, but all have access to the one variable. Also, make sure the world changes the value back to false when it acts on a true value.
lgbrf lgbrf

2012/5/3

#
that worked well thankyou, the problem was it wasnt a static boolean
danpost danpost

2012/5/3

#
There were ways of getting the value without making it static, but a bit more involved. Like
Player player = (Player) getObjects(Player.class).get(0);
if (player.mutating)
{
    player.mutating = false;
    addObject(new ...
lgbrf lgbrf

2012/5/3

#
ah ok, yeah this way works fine so i think ill stick with it :)
davmac davmac

2012/5/4

#
One reason to avoid static is that the value won't be reset when you use the "reset" button in Greenfoot. FWIW one of the tutorials (see the documentation) answers your question quite thoroughly.
You need to login to post a reply.