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.)
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.
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.
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.