This site requires JavaScript, please enable it in your browser!
Greenfoot back
thinud.bothma@reddam.house
thinud.bothma@reddam.house wrote ...

2025/6/10

World Management

Will the previous world be garbage collected once I instantiate a new world. Example: I have a world "Intro" and instantiate a world "Map", will Intro still be active?
danpost danpost

2025/6/10

#
thinud.bothma@reddam.house wrote...
Will the previous world be garbage collected once I instantiate a new world. Example: I have a world "Intro" and instantiate a world "Map", will Intro still be active?
No. However, if you set that Map world active, the Intro world will no longer be active. If you need to return to that same Map world instance, a reference must be kept on that instance in an active class field. One way to do this is to only allow one instance to be created from the Map class and have it keep a reference to that instance in a "static Map" field which can be then easily accessed from any other class. Something like the following should be sufficient to never create more than one instance:
 import greenfoot.*;

public class Map extends World 
{
    private static Map mapInstance;
    
    private Map() {
        super(600, 400, 1);
        // ...
    }
    
    // return the current Map instance, if exists; if not, create and return one
    public static Map getMap() {
        if (mapInstance == null) mapInstance = new Map();
        return(mapInstance);
    }
    
    // return a new Map instance
    public static Map getNewMap() {
        mapInstance = null;
        return getMap();
    }
    
    // ...
}
With the two added static methods and a private constructor, you have full control of exactly one Map instance at a time:
/** from another class */
// getting the current map
Map map = Map.getMap();
// or
// creating a new map
Map map = Map.getNewMap();
Thank you! work very well.
You need to login to post a reply.