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

2017/11/30

How do I use a int variable from MyWorld in an Actor class

Bonobo Bonobo

2017/11/30

#
Hello. I would like to use the variable "money", wich i created in MyWorld, in an actor. I tried the following, but it didnt work. Ty for any help guys. Im new to all of this, so pls be kind :)
//in MyWorld class





[code]//in MyWorld class
public int money = 300;


//in actor class
int myWorldMoney = ((MyWorld) getWorld()).money();
Super_Hippo Super_Hippo

2017/11/30

#
If you remove the last pair of () in line 12 and if line 12 is in a method where the actor is in the world (for example the act method), then it would work. However, the better way is to use a getter method and make the money variable in world private.
private int money = 300;

public int getMoney()
{
    return money;
}
int myWorldMoney = ((MyWorld) getWorld()).getMoney();
This version is still only working when the object is in the world. (So for example not in the constructor of the actor class.)
Bonobo Bonobo

2017/11/30

#
Alright. Thanks a lot :)
You need to login to post a reply.