Disposing of elements in a ring

Viewed 26

I'm trying to create a ring of spheres on Three.js, with a control for the number of spheres in the ring. Every time I change the control and run the function, I would like to dispose the previous ring so that it can be replaced by the new one. However, while the new ring appears, only one sphere seems to be getting disposed. The solution seems simple but I can't understand what's going wrong:

const params = {}
params.num = 10

let geometry = null
let material = null
let sphere = null

function generateMandala() {

//Destroy Materials. This is the problem: only a single sphere is getting destroyed.
  if (sphere !== null) {
    geometry.dispose()
    material.dispose()
    scene.remove(sphere)
  }

  geometry = new THREE.SphereGeometry(0.25, 32, 32)
  material = new THREE.MeshBasicMaterial()

//Create Ring
  let radius = 2
  let angle = (Math.PI * 2) / params.num

  for (let i = 0; i < params.num; i++) {

    let x = Math.sin(i * angle) * radius
    let y = Math.cos(i * angle) * radius

    sphere = new THREE.Mesh(geometry, material)
    sphere.position.set(x, y, 0)

    scene.add(sphere)
  }
}

generateMandala()

gui.add(params, 'num').min(1).max(50).onFinishChange(generateMandala)

Thanks in advance!

1 Answers

Solved! By adding into a group, then disposing of the entire group :)

let geometry = null
let material = null
let sphere = null
let group = null

function generateMandala() {

  if (sphere !== null) {
    geometry.dispose()
    material.dispose()
    scene.remove(group)
  }

  geometry = new THREE.SphereGeometry(0.25, 32, 32)
  material = new THREE.MeshBasicMaterial({
    color: new THREE.Color(1, random(0, 1), random(0, 1))
  })
  group = new THREE.Group();

  let radius = 2
  let angle = (Math.PI * 2) / params.num

  for (let i = 0; i < params.num; i++) {

    let x = Math.sin(i * angle) * radius
    let y = Math.cos(i * angle) * radius

    sphere = new THREE.Mesh(geometry, material)
    sphere.position.set(x, y, 0)

    group.add(sphere)
  }
  scene.add(group)
}

generateMandala()
Related