Update InstancedMesh geometry and material

Hello!

Is it possible to update an instanced mesh with new geometries and materials after creation?

For example:

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const test = new THREE.InstancedMesh(geometry, material, 9);
test.instanceMatrix.setUsage(THREE.DynamicDrawUsage); // will be updated every frame
this.scene.add(test);
for (let i = 0; i < 9; i++) {
  const pos = new THREE.Vector3(Math.random() * 3, Math.random() * 3, Math.random() * 3);
  const rot = new THREE.Quaternion();
  const scale = new THREE.Vector3(1, 1, 1);
  test.setMatrixAt(i, new THREE.Matrix4().compose(pos, rot, scale));
}
setTimeout(() => {
  const geometry2 = new THREE.SphereGeometry(15, 32, 16);
  const material2 = new THREE.MeshBasicMaterial({ color: 0x0000ff });
  test.geometry = geometry2;
  test.material = material2;
  this.render();
}, 15000);

I’ve tested it here and it works as expected: Edit fiddle - JSFiddle - Code Playground

You should also call dispose() on the previous geometry and material if you are going to replace them.

1 Like

Yes I will. Sorry, small blunder on my part. They didn’t show up due to the replacing sphere’s size, causing the camera to be inside :man_facepalming:

Thanks for the help anyway!