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

2011/7/17

How to use added to world?

kiarocks kiarocks

2011/7/17

#
I've looked but i am confused how you put the world name in the ().
DonaldDuck DonaldDuck

2011/7/17

#
protected void addedToWorld(World world)
{
    write stuff here
}
The World called "world" in that void will be whatever world the object was added to.
kiarocks kiarocks

2011/7/18

#
so i have to write that before i can call in a if statement?
danpost danpost

2011/7/18

#
Hey kiarocks, the method 'addedToWorld' which is placed in the Actor class code is automatically called by Greenfoot when you 'addObject(actor, x, y)'; it is not something you call yourself. Anytime an actor of said type is added into the world, the code for 'addedToWorld' you write within your 'addedToWorld' method will execute. (Thanks, DonaldDuck. It is always good to clarify that which may not be totally clear.)
kiarocks kiarocks

2011/7/18

#
oh, i just thought of a way to do it-what this was going to do
DonaldDuck DonaldDuck

2011/7/18

#
danpost wrote...
Hey kiarocks, the method 'addedToWorld' which is placed in the Actor class code is automatically called by Greenfoot when you 'addObject(actor, x, y)'; it is not something you call yourself. Anytime an actor of said type is added into the world, the code for 'addedToWorld' will execute.
Yes, it is executed when the object is added to the world, but it has to be present in your code to be executed.
DonaldDuck DonaldDuck

2011/7/18

#
kiarocks wrote...
so i have to write that before i can call in a if statement?
Not necessarily. The addedToWorld method can be handy to: 1. Find the position of the object before the program actually starts 2. Define the World object as a World so you don't have to always call ((myWorld) getWorld())., you can just define world and call world. 3. Affect a variable only once when the object is added to the world (so you can keep an internal could of how many have been added for example) Or any number of similar reasons.
mjrb4 mjrb4

2011/7/20

#
As above you don't have to put that method in or do anything with it at all. It's just useful if you've got something you want to do to each time that actor is inserted into the world. Not sure if this is relevant here or not, but if you're not sure you've declared the method properly (it won't get called unless the signature matches exactly you can use @Override straight before the method declaration:
@Override
protected void addedToWorld(World world)  
{  
    write stuff here  
} 
If you use that and you haven't declared the method properly it'll fail at compile time rather than just fail silently at runtime, which makes things much easier to solve bug-wise! I use that annotation quite a lot outside of Greenfoot too, it's a useful one to know.
You need to login to post a reply.