gui 初始化后如何销毁

threejs yekong

three项目开发中会集成gui插件用来做一些交互,因为项目需要多次初始化,导致gui也重复初始化出现了多个gui插件,这时候我们需要销毁旧的避免出现多个gui界面。

旧代码

import {GUI} from 'three/examples/jsm/libs/lil-gui.module.min.js';
const initGui = () => {
  let gui = new GUI();
  const guiParams = {
    topColor: '#b4eeea',
    sideColor: '#123024',
    scale: 0.1,
  };
  gui.addColor(guiParams, 'topColor').onChange((val) => {
    topFaceMaterial.color = new THREE.Color(val);
  });
  gui.addColor(guiParams, 'sideColor').onChange((val) => {
    sideMaterial.color = new THREE.Color(val);
  });
  gui.add(guiParams, 'scale', 0, 1).onChange((val) => {
    textureMap.repeat.set(val, val);
    texturefxMap.repeat.set(val, val);
  });
};

修改后

将gui提取出来,初始化之前判断gui是否已经初始化了,如果初始化了则销毁重新初始化。

import {GUI} from 'three/examples/jsm/libs/lil-gui.module.min.js';
let gui;
const initGui = () => {
  if (gui) {
    gui.destroy();
    gui = null;
  }
  gui = new GUI();
  const guiParams = {
    topColor: '#b4eeea',
    sideColor: '#123024',
    scale: 0.1,
  };
  gui.addColor(guiParams, 'topColor').onChange((val) => {
    topFaceMaterial.color = new THREE.Color(val);
  });
  gui.addColor(guiParams, 'sideColor').onChange((val) => {
    sideMaterial.color = new THREE.Color(val);
  });
  gui.add(guiParams, 'scale', 0, 1).onChange((val) => {
    textureMap.repeat.set(val, val);
    texturefxMap.repeat.set(val, val);
  });
};
喜欢