Skip to content

Add Custom Data

If an array of instances has been created, you can assign custom data to each instance:

type CustomData = { uuid: string };
const iMesh = new InstancedMesh2<CustomData>(geo, mat, { createEntities: true });
iMesh.addInstances(count, (obj, index) => {
obj.uuid = MathUtils.generateUUID();
});

Example

import { InstancedMesh2 } from '@three.ez/instanced-mesh';
import { MeshStandardMaterial, TorusKnotGeometry } from 'three';
type CustomData = { startScale: number };
const geo = new TorusKnotGeometry();
const mat = new MeshStandardMaterial()
export const torusKnots = new InstancedMesh2<CustomData>(geo, mat, { createEntities: true });
torusKnots.addInstances(9, (obj, index) => {
obj.position.x = (index % 3 - 1) * 5;
obj.position.y = (Math.trunc(index / 3) - 1) * 5;
obj.quaternion.random();
obj.color = Math.random() * 0xffffff;
obj.startScale = Math.random();
obj.scale.setScalar(obj.startScale);
});
torusKnots.on('animate', (e) => {
torusKnots.updateInstances((instance) => {
instance.rotateZ(e.delta);
instance.scale.setScalar(Math.abs(Math.sin(instance.startScale + e.total)));
});
});
import { Scene, DirectionalLight, AmbientLight } from 'three';
import { Main, PerspectiveCameraAuto } from '@three.ez/main';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { torusKnots } from './app.js';
const main = new Main();
const camera = new PerspectiveCameraAuto().translateZ(20);
const scene = new Scene().add(torusKnots);
main.createView({ scene, camera });
const controls = new OrbitControls(camera, main.renderer.domElement);
controls.update();
const ambientLight = new AmbientLight('white', 0.8);
scene.add(ambientLight);
const dirLight = new DirectionalLight('white', 2);
dirLight.position.set(0.5, 0.866, 0);
camera.add(dirLight);