I'm using P5.js to create two scenes
A global variable currentScene
instantiates the Scene to be rendered.
Then I have two scene classes:
Now, the button New Game is creates inside the class MainMenu, so when currentScene no longer points to MainMenuScene, I'd expect the instance to be garbage collected, and since the button is an attribute of the class, I'd expect it to also be garbage collected.
However, it looks like although the scene correctly changes to CombatScene (red background) the button remains there.
Why does it remain there, and how can I get rid of it?
Does the button "surviving" mean that it's preventing the MainMenu instance from being garbage collected?
class MainMenuScene {
constructor() {
// button is an attribute of the class,
//so when the instance of theclass is garbage collected
// it should disappear, but it doesn't
this.button = createButton("New Game");
this.button.position(100, 100);
this.button.mousePressed(() => {
// here currentScene changes to CombatScene, so the instance of
// MainMenuScene should be garbage collected, right?
currentScene = new CombatScene();
});
}
show() {
background("blue");
}
}
class CombatScene {
constructor() {}
show() {
background("red");
}
}
let currentScene;
function setup() {
createCanvas(400, 400);
currentScene = new MainMenuScene();
}
function draw() {
currentScene.show();
}
In p5.js there is a remove() method which removes the button from canvas. You can use this method for your solution.
class MainMenuScene {
constructor() {
// button is an attribute of the class,
//so when the instance of theclass is garbage collected
// it should disappear, but it doesn't
this.button = createButton("New Game");
this.button.position(100, 100);
this.button.mousePressed(() => {
// here currentScene changes to CombatScene, so the instance of
// MainMenuScene should be garbage collected, right?
currentScene = new CombatScene();
this.button.remove(); // removes the button after scene is switched
});
}
show() {
background("blue");
}
}
class CombatScene {
constructor() {}
show() {
background("red");
}
}
let currentScene;
function setup() {
createCanvas(400, 400);
currentScene = new MainMenuScene();
}
function draw() {
currentScene.show();
}