类取消实例化时按钮不会被销毁

问题描述 投票:0回答:1

我正在使用 P5.js 创建两个场景

全局变量

currentScene
实例化要渲染的场景。

然后我有两个场景类:

  • MainMenuScene,带有一个实例化 CombatScene 的按钮 New Game
  • 我将在其中渲染我的游戏的战斗场景。

现在,按钮 New Game 是在类 MainMenu 中创建的,因此当 currentScene 不再指向 MainMenuScene 时,我希望该实例被垃圾收集,并且由于该按钮是该类的属性,因此我希望它也被垃圾收集。

但是,虽然场景正确更改为 CombatScene(红色背景),但按钮仍保留在那里。

为什么它会留在那里?我怎样才能摆脱它?

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();
}
javascript garbage-collection p5.js
1个回答
0
投票

在p5.js中有一个remove()方法,可以从画布上删除按钮。您可以使用此方法来解决您的问题。
类主菜单场景{ 构造函数(){

    // 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();
}
© www.soinside.com 2019 - 2024. All rights reserved.